I have text that contains links and link of an images and there can have a lot of link and mix with other words. The text below is my example text.
$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##";
I want to use preg_replace
to replace them like this.
$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>';
This is preg_replace
pattern for links.
$string = preg_replace("/([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])/i","<a target=\"_blank\" href=\"$1\">$1</a>",$string);
This is preg_replace
for pictures.
$string = preg_replace("/\#\#([\w]+:\/\/[\w-?&;#~=\.\/\@]+[\w\/])\#\#/i","<img src=\"$1\"></img>",$string);
Both of them work well, but they don't separate between links and image links. Please help me thanks I've tried all day.
Because the only reliable difference between the links are the # hash marks, I think you need to use the Positive Lookbehind to add another layer of uniqueness between the regexes.
The first regex looks for URLs without hash marks to make those anchor tags
/((?<!##)https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])/i
Then, look for any links with hash marks and make those img tags
/\#\#(https?:\/\/[\w-?#&;~=\.\/\@]+[\w\/])\#\#/i
I also had to replace [\w]+: at the start of each regex with something more specific because \w appears to match #, so I changed [\w]+: with https?: to match http: or https:
So the final two-piece regex looks like this
$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);
I ran a test on this and it appeared to work for me using your example.