Forum Moderators: coopster

Message Too Old, No Replies

Regular expression problem

regular expressions

         

flairview

5:02 pm on Jun 17, 2005 (gmt 0)

10+ Year Member



I've been trying to work this out and keep getting no where.
Basicly what i need is to, replace any string that is not within an <a href></a> tag. So say if i am trying to replace:

$string = '<a href="test.php">test site</a> site';

If wanted to replace the word "site" with <a href="site.php">site</a>, but at the same time not to touch the word "site" inside the first <a> tag.
To get the following result:
$string = '<a href="test.php">test site</a> <a href="site.php">site</a>';
Anyone ever done this by any change?

Regards,

fv

flairview

8:00 am on Jun 18, 2005 (gmt 0)

10+ Year Member



I created something that does this job, but its has lots of bugs:

$desc='<a href="test.php">test</a> test, <b>test</b> <a href="test.php">a test is a test</a>';
$string = 'test';

$pattern = "/(?![^<]*>)\b(?<!\">)(".$string.")(?!<\/a>)\b/i";
$replacement = '<a href="'.$string.'">'.$string.'</a>';
$desc = preg_replace($pattern, $replacement, $desc);

echo $desc;

output: <a href="test.php">test</a> <a href="test">test</a>, <b><a href="test">test</a></b> <a href="test.php">a <a href="test">test</a> is a test</a>

Desired output: <a href="test.php">test</a> <a href="test">test</a>, <b><a href="test">test</a></b> <a href="test.php">a test is a test</a>

Any ideas?

Thanks,

fv