0

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?

bear87
  • 83
  • 1
  • 11
  • 1
    Try changing `if(strpos($example,$kw))` to `if(strpos($example,$kw) !== false)`. If the string you're looking for is the first thing,`stpost` will return `0` (which will evaluate as `false`). You can read more under "Return value" in [the manual](https://www.php.net/manual/en/function.strpos.php) about what it returns – M. Eriksson Mar 02 '21 at 06:37

1 Answers1

1

Function strpos return position of element.

If element has first position, than it's return 0 (zero).

But if statement represent zero as false. That why it's doesn't work.

Just change your if statement, like this:

//old
if(strpos($example,$kw)) {

//new
if (strpos($example,$kw) !== false) {

read more about strpos in docs

https://www.php.net/manual/ru/function.strpos.php

By the way read this

Null vs. False vs. 0 in PHP