PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!
Hey im currently using str_replace to highlight words in a search results page. First its not case insensitive because its not str_ireplace, so thats not a problem. But the problem is that when I replace the strings it only highlights the exact phrase. I.e.
$cid = "Please dont ask";
$verse = "I have to go Please I am running late, dont ask, Please dont ask";
$d = str_replace( $cid, "<span style='color:red'>".$cid."</span>", $verse);
echo $d;
Returns: I have to go Please I am running late, dont ask, Please dont ask
The words highlighted in yellow dont get highlighted, I know why but can anyone suggest of a way to explode the words and then use str_replace so that I can highlight all the words even if they are not mentioned together.
// assumes $cid is your query string, and $verse is your body text
$highlighted = array();
$words = explode(' ', $cid);
foreach ($words as $word)
{
$highlighted[] = '<span style="color:red">'.$word.'</span>';
}
echo str_replace($words, $highlighted, $verse);
Ok Im having this problem where if a word is inside a qoutes (" ") that will not be seen as a separate word i.e "Good things happen" only the word things gets highlighted (str_replace) where as the words "Good and things" dont get replaced, i know its because those words have the quotes attached to it but is there a way to resolve this, I know I can use regex to do this but is there an easier way?
$cid =array("Please","dont","ask");
$cidReplace =array("<span style='color:red'>Please</span>","<span style='color:red'>dont</span>","<span style='color:red'>ask</span>");
$verse = "I have to go Please I am running late, dont ask, Please dont ask";
$d = str_replace( $cid, $cidReplac, $verse);
echo $d;