Page 1 of 1

automatic replacement of text

Posted: Wed Sep 24, 2008 7:53 am
by paulopocas
Hello

I'm building a site that is heavy on PHP and MySQL and I'm a self learner newcomer so I have some doubts, most I can work out myself others I can search the web for answers with a fair amount of success, others like this one I don't even know how to look for it :D

My question is this:

There will be inside a field on a table some entries in the middle of a text like <http://www.somewhere.com Somewhere you should go> and I want php to resolve this text and output something like <a href="http://www.somewhere.com">Somewhere you should go</a>. Of course this text is only is only a stand in and there could be a lot of this kind of entries so it would need to be fully automatic and search the entire text for them.

Thanks in advance

Re: automatic replacement of text

Posted: Wed Sep 24, 2008 8:04 am
by papa
preg_replace should do it.

Re: automatic replacement of text

Posted: Wed Sep 24, 2008 9:09 am
by Darkzaelus
paulopocas wrote:<http://www.somewhere.com Somewhere you should go> and I want php to resolve this text and output something like <a href="http://www.somewhere.com">Somewhere you should go</a>.

Thanks in advance

Code: Select all

 
$text='<http://www.somewhere.com Somewhere you should go>';
$new=preg_replace('/\\<((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))\\s(.*?)\\>/is','<a href="$1">$2</a>',$text);
echo $new //<a href="http://www.somewhere.com">Somewhere you should go</a>
 
:)

If I were you, I would use square brackets instead of greater, and less than signs. Keep it seperate from XML style tags if possible. If you want to do that, use:

Code: Select all

 
$text='[http://www.somewhere.com Somewhere you should go]';
$new=preg_replace('/\\[((?:http|https)(?::\\/{2}[\\w]+)(?:[\\/|\\.]?)(?:[^\\s"]*))\\s(.*?)\\]/is','<a href="$1">$2</a>',$text);
echo $new //<a href="http://www.somewhere.com">Somewhere you should go</a>
 
Darkzaelus