Forum Moderators: coopster

Message Too Old, No Replies

Dynamically change a word to a link

change first occurance of specific word to a hyperlink

         

wheelie34

11:49 am on Jun 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Hi

I have a script (I think I found it here some time ago) that checks for existance of a specific word, if found, it changes it to a hyperlink still with the same word.

I would like it to only change the first occurance of the word though, currently it changes every occurance.

$sql="select * from table where num='$num'";
$result = mysql_query($sql, $dblink) or die("System down");
$pairs = array(

'word1' => '<a href="http://www.example.com/">word1</a>',
'word2' => '<a href="http://www.example2.com/">word2</a>',

);

while ($newArray = mysql_fetch_array($result)){
$num = $newArray['num'];
$title = $newArray['title'];
$text = str_replace(array_keys($pairs), array_values($pairs), $newArray['text']);
}

How should I go about it? thanks in advance

eelixduppy

1:17 pm on Jun 16, 2007 (gmt 0)



You can use preg_replace [php.net] and specify the LIMIT parameter to 1.

wheelie34

3:08 pm on Jun 16, 2007 (gmt 0)

WebmasterWorld Senior Member 10+ Year Member



Thanks eelixduppy worked perfect, for anyone else looking heres the changes.

had to add / before and after each word to find

'/word1/' => '<a href="http://www.example.com/">word1</a>',
'/word2/' => '<a href="http://www.example2.com/">word2</a>',

replaced str_replace with preg_replace and added the , 1 to limit the changes to the first instance of the word to change

$text = preg_replace(array_keys($pairs), array_values($pairs), $newArray['story'], 1);

Thanks again