automatic replacement of text

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
paulopocas
Forum Newbie
Posts: 1
Joined: Wed Sep 24, 2008 7:50 am

automatic replacement of text

Post 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
User avatar
papa
Forum Regular
Posts: 958
Joined: Wed Aug 27, 2008 3:36 am
Location: Sweden/Sthlm

Re: automatic replacement of text

Post by papa »

preg_replace should do it.
Darkzaelus
Forum Commoner
Posts: 94
Joined: Tue Sep 09, 2008 7:02 am

Re: automatic replacement of text

Post 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
Post Reply