I am making a class in PHP that detects the social network or instant messaging platform of a given URL:
class SocialLinkParser
{
const TELEGRAMM='telegramm';
const WHATSUP='whatsup';
const YOUTUBE='youtube';
const INSTAGRAMM='instagram';
const LINKEDIN='linkedin';
const TWITTER='twitter';
const FACEBOOK='facebook';
const PINTEREST='pinterest';
const REDDIT='reddit';
const URL_MAPPINGS = [
'tg'=>self::TELEGRAMM,
't.me'=>self::TELEGRAMM,
'wa.me'=>self::WHATSUP,
'youtu.be'=>self::YOUTUBE,
'instagr.am'=>self::INSTAGRAMM,
'lnkd.in'=>self::LINKEDIN,
't.co'=>self::TWITTER,
'x.com'=>self::TWITTER,
'fb.me'=>self::FACEBOOK,
'pin.it'=>self::PINTEREST,
'redd.it'=>self::REDDIT
];
const SCHEME_MAPPINGS=[
'tg'=>self::TELEGRAMM,
];
public static function parse($link):string
{
$parsedLink = parse_url($link);
$scheme = strtolower($parsedLink['scheme']);
// Invitation links may not start with http
if(!str_contains($scheme, 'http')){
return self::SCHEME_MAPPINGS[$scheme]??$scheme;
}
$path = strtolower($parsedLink['path']);
$domainParts = explode('.', $path);
//remove last part. It is gtld
array_pop($domainParts);
return self::URL_MAPPINGS[$path]??trim(array_pop($domainParts));
}
}
The idea is to detect the social network name for known socials depending the url format. I check both invitation links for whatup, telegramm, etc., and also known shortened urls that each network generates.
Somehow I want a mechanism that generates a specific value for each social network so I can decide later what Icon to render if render a list links into html. Thus making a unique string for each social helps me to have a map with available social Icons. The mechanism is implemented seperately in order to be flexible.
Edit1 Context
I am into a situation where I want to display these icons depending the social network of a URL (for example in a config social_icons.php
):
<?php
return [
'facebook'=> 'bi bi-facebook',
'twitter'=> 'bi bi-twitter',
'instagram'=> 'bi bi-instagram',
'youtube'=> 'bi bi-youtube',
'twitch'=>'bi bi-twitch',
'telegram'=> 'bi bi-telegram',
'viber'=> 'bi bi-viber',
'skype'=> 'bi bi-skype',
'reddit'=>'bi bi-reddit',
];
And for that I need to calculate the nessesary key for it. A usage example is:
$icons = require_once('icons.php');
$url = htmlspecialchars(($_POST['url']??""), ENT_QUOTES, 'UTF-8')
$icon = SocialLinkParser::parse($url)??"bi bi-link"
echo "<i class='$icon'></i> <a href=\"$url\">$url</a>";
I want to configure the nessesary icon into a seperate file so I approached it like this.
A possible input is:
- IM invitation Links for example skype (skype:skype_username?call)
- Http links for known services: http://instagram.com
telegramm
andwhatsup
are improper spellings. This may not be a problem since they are associated constants, but this just hurts... \$\endgroup\$