Forum Moderators: coopster

Message Too Old, No Replies

[How to] Exclude replacement inside hyperlinks, maybe using if statement,or other way

         

basketmen

11:09 pm on Apr 19, 2011 (gmt 0)

10+ Year Member



Hi guys, below are simple script for word replacement, it is replacing a word in to link



[PHP]$word = array(
'google',
'yahoo'
);

$link = array(
'<a href="http://google.com">google</a>',
'<a href="http://yahoo.com">yahoo</a>'
);


$this->post['message'] = str_ireplace($word, $link, $this->post['message']);[/PHP]







for example text
i love google result


the output printed will be like this
[HTML]i love <a href="http://google.com">google</a> result[/HTML]

it is just replacing google text into a link like this <a href="http://google.com">google</a>








but the problem is if the original google text is already inside a link, like this
[HTML]<a href="http://google.com">i love google result</a>[/HTML]

the output printed will be broken like this, there will be double hyperlink
[HTML]<a href="http://google.com">i love <a href="http://google.com">google</a> result</a>[/HTML]







please help guys, how to exclude the text google inside hyperlinks above from replaced, but the text google outside hyperlinks are still replaced

maybe using if statement in the simple script above, or other way

Mahabub

8:48 am on Apr 20, 2011 (gmt 0)

10+ Year Member




check the below code

$word = array(
'google',
'yahoo'
);

$link = array(
'<a href="http://google.com">google</a>',
'<a href="http://yahoo.com">yahoo</a>'
);

$message = 'i love google';

$message = str_ireplace($word, $link,$message);

echo $message;

basketmen

2:13 am on Apr 21, 2011 (gmt 0)

10+ Year Member



thanks for answering, but i am afraid its not working, nothing changed, any other code or other way please?

rocknbil

6:59 pm on Apr 21, 2011 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Just strip out all the links with the keywords, you'd likely want to do that anyway. This might be fragile but it will work.


<?php
$string = '
<p>but the problem is if the original google text is already inside a link, like this
<a href="http://google.com">i love google result</a></p>
<p>I love yahoo</p>
<p>No Google is better</p>
<p>Bingo, boingo, bongo.</p>
<p>Doesn\'t anyone remember Lycos?</p>
';
echo "<p>Before</p> $string";
$links = Array(
'Google' => 'http://google.com',
'Yahoo' => 'http://yahoo.com',
'Bing' => 'http://www.bing.com',
'Lycos' => 'http://www.lycos.com'
);
foreach ($links as $key => $value) {
$strip = "<a[^>]+>.*" . $key . "[^<]*<\/a>";
$string = preg_replace("/$strip/ism",$key,$string);
$string = preg_replace("/$key/im","<a href=\"$value\">$key</a>",$string);
}
echo "<p>After</p> $string";
?>


Note it is case insensitive and properly capitalizes the entities.