Jump to content

preg_replace - Stop from replacing matching img filename


surfwtw

Recommended Posts

I am wanting to replace certain words to make them bold and also linked. The code below is working however it is also replacing images that have the same filename therefore causing the image to be broken.  How can I replace the word when it appears without replacing the filename when it appears.

 

<?php

 

$find = array ("/$word/i","/A Duty of Care/i");

 

$replace = array ("<a href=/link.php?word=$word><b>$word</b></a>","<a href=/link.php>A Duty of Care</a>");

 

 

Echo preg_replace ($find, $replace, $definition);

 

?>

Do you that, for example, if your $word is "bob" that all images within the $definition with "bob" in their image name are also being replaced?

 

This is a great question and I googled it and many other forums had the same question but no concrete answer. I am going to think about this alot bc while there may be very difficult ways to do it(like something that parses every word in the string of text and replaces the word only if it's not within a tag) but there must be an easier way to do it.

Yeah the only solution I have found is only replace once and then go to my database, copy and paste the filename above the file as if it is an image title. That way if a word is being replaced it won't ruin the file. I have spent days searching trying to figure this out.  I have a code that works to search and replace words to make them bold and it doesn't change the file name, it also works for linking the word but I haven't figured out a way to manipulate it so that it works for a large array of words. The code is below, if anyone can figure out how to get it to work for an array of more than one word then please let me know.  Look at the code below, what if instead of replacing "$word" with "<b>$word</b>" I wanted to replace (car, truck, boat) with (<b>car</b>,<b>truck</b>,<b>boat</b>.  All I know is that THIS CODE did not corrupt my files. It only changed the word when it appeared in text.

 

 

<?php

 

function boldWord($word,$definition){

 

$word = strtolower($word);

$ucf_word = ucfirst($word);

$uc_word = strtoupper($word);

return str_replace(array($word,$ucf_word,$uc_word), array("<b>$word</b>","<b>$ucf_word</b>","<b>$uc_word</b>"), $definition);

 

}

 

$text = "$definition";

echo boldWord("$word",$definition);

 

?>

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.