Web Hosting Talk







View Full Version : multiple eregi_replace / preg_replace : help


jayantk
03-06-2003, 05:31 AM
if "abc" and "abc def" have to be linked with URL1 and URL2
then in the text:
"kjkhj abc lkjhsdf abc def ljh"
I want the output as
"kjkhj <a href=URL1>abc</a> lkjhsdf <a href=URL2>abc def</a> ljh"
instead of
"kjkhj <a href=URL1>abc</a> lkjhsdf <a href=URL2><a href=URL1>abc</a> def</a> ljh"
or
"kjkhj <a href=URL1>abc</a> lkjhsdf <a href=URL1>abc</a> def ljh"

How can I achieve this ? PHP prefered. code sample in Perl will also do though

Thanks in advance.
Prize: A BMW to the one who answers this correctly ;)

jonaskb
03-06-2003, 05:55 AM
<?php
$string = "kjkhj abc lkjhsdf abc def ljh";

$string = preg_replace("/(abc def)/", "<a href='URI 2'>\\1</a>", $string);
$string = preg_replace("/([^>])(abc)/", "\\1<a href='URI 1'>\\2</a>", $string);
?>

This is how it works: First we find and replace all occurences of "abc def". Then we find and replace the "abc"s that do not have a ">" in front of them (cause the ones with ">" are the ones that are part of the "abc def" links we just made).

--
Jonas Koch Bentzen

http://findhim.com/

jayantk
03-06-2003, 06:03 AM
I just gave a special case, I am looking for a more generic answer

I have a array $strings
having data in form
$strings[0]="pattern/string 1";
$strings[1]="replace URL string 1";
$strings[2]="pattern/string 2";
$strings[3]="replace URL string 2";
$strings[4]="pattern/string 3";
$strings[5]="replace URL string 3";
$strings[6]="pattern/string 4";
$strings[7]="replace URL string 4";
...
...
...


I have text in variable $text.

I have to link all pattern/strings with the replace URL strings.