php - Create url links from a bunch of strings -



php - Create url links from a bunch of strings -

i have bunch of strings concatenated 1 contain text , links. want find urls in string , want set href each 1 (create link). using regular look pattern finding urls (links) in string. check illustration below:

example :

<?php // text want filter urls $text = "the text want filter goes here. http://google.com/abc/pqr 2the text want filter goes here. http://google.in/abc/pqr 3the text want filter goes here. http://google.org/abc/pqr 4the text want filter goes here. http://www.google.de/abc/pqr"; // regular look filter $reg_exurl = "/(http|https|ftp|ftps)\:\/\/[a-za-z0-9\-\.]+\.[a-za-z]{2,3}(\/\s*)?/"; // check if there url in text if (preg_match($reg_exurl, $text, $url)) { // create urls hyper links echo preg_replace($reg_exurl, "<a href='.$url[0].'>" . $url[0] . "</a> ", $text); } else { // if no urls in text homecoming text echo $text . "<br/>"; } ?>

but showing next output :

> text want filter goes here. **http://google.com/abc/pqr** 2the > text want filter goes here. **http://google.com/abc/pqr** 3the text > want filter goes here. **http://google.com/abc/pqr** 4the text > want filter goes here. **http://google.com/abc/pqr**

whats wrong this?

as regex delimited slashes, need careful when regular look contains them. often, it's easier utilize different characters delimit regular expression: php doesn't mind use.

try replacing first , lastly "/" characters character, e.g. "#" , code work.

you simplify code , whole thing in 1 phone call preg_replace follows:

<?php $text = 'the text want filter goes here. http://google.com/abc/pqr 2the text want filter goes here. http://google.in/abc/pqr 3the text want filter goes here. http://google.org/abc/pqr 4the text want filter goes here. http://www.google.de/abc/pqr'; echo preg_replace('#(http|https|ftp|ftps)\://[a-za-z0-9-.]+.[a-za-z]{2,3}(/\s*)?#i', '<a href="$0">$0</a>', $text);

php regex

Comments

Popular posts from this blog

web services - java.lang.NoClassDefFoundError: Could not initialize class net.sf.cglib.proxy.Enhancer -

Accessing MATLAB's unicode strings from C -

javascript - mongodb won't find my schema method in nested container -