I'm retrieving some data from a MySQL database. For highlighting purposes, I want to modify the displayed data using PHP. A span class is added which will apply some text colouring and letter-spacing. My data is stored in $example
.
This is my PHP code so far, $kw
is the variable which contains the string to be replaced:
$kw = "Fun:"
if(strpos($example,$kw)) {
$example = str_replace($kw,"<span class='new'>Fun:</span>",$example);
}
This works fine for $example = "text text; Fun: text";
. As for something like $example = "Fun: text";
, "Fun:" is not replaced as expected, str_replace is not applied. Literally nothing happens.
When I try to replace $kw = "un:";
instead, it works fine, besides The "F" in "Fun:" is now missing the highlighting.
So if the text to be replaced is at the beginning of the search string, nothing happens. It seems that str_replace starts looking at the second character of the string instead of the beginning. I cannot figure out why.
I checked the array where the query results are stored, but found no hints which could help me solve this issue. I also printed the result from strpos for both cases. As for the first example, I got an integer > 0, for the second example the result gave 0. This seems to be fine, since in example 1 $kw
is somewhere inbetween other text whereas in example 2 it is at the beginning of the line.
Did anyone ever came across this issue or am I too blind to see the solution here?