我有包含链接和图像链接的文本,并且可以有很多链接并与其他单词混合。下面的文本是我的示例文本。
$string = "http://www.google.com/ is best know for search engine, this is Google logo ##https://www.google.com/images/srpr/logo11w.png##. And you can visit http://www.youtube.com/ to watch videos. Here YouTube's logo ##http://s.ytimg.com/yts/img/pixel-vfl3z5WfW.gif##";
我想用preg_replace
这样的方式替换它们。
$string = '<a href="http://www.google.com/">http://www.google.com/</a> is best know for search engine, this is Google logo <img src="https://www.google.com/images/srpr/logo11w.png" />. And you can visit <a href="http://www.youtube.com/">http://www.youtube.com/</a> to watch videos. Here YouTube's logo <img src="http://s.ytimg.com/yts/img/pixel-vfl3z5WfW.gif"></img>';
这是preg_replace
链接的模式。
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string);
这是preg_replace
用于图片。
$string = preg_replace("/\#\#([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])\#\#/i","<img src=\"$1\"></img>",$string);
它们都可以正常工作,但是它们不能在链接和图像链接之间分开。请帮助我,谢谢我整天尝试。
因为链接之间唯一可靠的区别是#井号,所以我认为您需要使用正向后隐藏在正则表达式之间添加另一层唯一性。
第一个正则表达式查找没有哈希标记的URL ,以使这些锚标记
/((?<!##)https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])/i
然后,查找带有哈希标记的任何链接,并使其成为img标签
/\#\#(https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])\#\#/i
我还必须在每个正则表达式的开头用更具体的内容替换[\ w] + :,因为\ w似乎与#匹配,所以我将[\ w] +:替换为https ?:以匹配http:或https:
所以最后的两部分正则表达式看起来像这样
$string = preg_replace("/((?<!##)https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string);
$string = preg_replace("/\#\#(https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])\#\#/i","<img src=\"$1\"></img>",$string);
我对此进行了测试,并使用您的示例对我似乎有用。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句