我使用preg_replace做了一些功能。代码是为了预览它。
我制作了这段代码
$strings = htmlspecialchars_uni($thread['soc_instagram']);
$searchs = array('~(?:https://instagram\.com/p/)?([a-zA-Z0-9_\-+?:]+)~');
$replaces = array('https://instagram.com/p/$1/media/?size=l');
$soc_instagram = preg_replace($searchs,$replaces,$strings);
如果我使用此网址https://instagram.com/p/BarUcqwht_u
发布Instagram,则代码可以完美运行它将生成代码
https://instagram.com/p/BaQsAubg6H3/media/?size=l
但问题是当我尝试在网址中添加WWW时,类似这样的https://www.instagram.com/p/BarUcqwht_u代码会产生错误字符串
结果将是这样的
https://instagram.com/p/https:/media/?size=l//https://instagram.com/p/www/media/?size=l.https://instagram.com/p/instagram/media/?size=l.https://instagram.com/p/com/media/?size=l/https://instagram.com/p/p/media/?size=l/https://instagram.com/p/BarUcqwht_u/media/?size=l/
我尝试在我的preg_replace代码中添加WWW,但结果将是这样的
https://www.instagram.com/p/https:/media/?size=l//https://www.instagram.com/p/instagram/media/?size=l.https://www.instagram.com/p/com/media/?size=l/https://www.instagram.com/p/p/media/?size=l/https://www.instagram.com/p/BaQsAubg6H3/media/?size=l
任何帮助都会很好,谢谢
答案 0 :(得分:0)
在协议之后添加www.
并使其成为可选项。 preg_replace
也不需要数组,字符串工作正常。
$strings = 'https://www.instagram.com/p/BarUcqwht_u';
$searchs = '~(?:https://(?:www\.)?instagram\.com/p/)?([a-zA-Z0-9_\-+?:]+)~';
$replaces = 'https://instagram.com/p/$1/media/?size=l';
$soc_instagram = preg_replace($searchs,$replaces,$strings);
echo $soc_instagram;
您当前的实现所做的是用URL替换字符类中未列出的字符。有关直观表示,请参阅https://regex101.com/r/PXb2h1/2/。