Home > database >  PHP preg_replace priblem with /
PHP preg_replace priblem with /

Time:10-28

I use the following code for checking for a sting and highlight the found sting in a text:

echo preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$value); 

The problem comes when I enter to search only one special character like / or * . Then give me an error:

Warning: preg_replace(): Unknown modifier '[' in C:\xampp... However if i try to search " test/test" all is ok, no errors.

The problem is that I need to search in text word strings like: location*code/1334 -> and works but not highlight them if they contains special characters. Also wish if the user enter for search argument only / or * to tell him: nothing found , instead of error.

Full code:

$found = false;

foreach ($arr_string as $value) {
    if(stripos($value, $text) !== false) {
        echo preg_replace("/\b([a-z]*${fwcode}[a-z]*)\b/i","<font color ='red'><b>$1</b></font>",$value);
        $found = true;
    } 
}

if (!$found) {
    echo "No such word";
}

--- ? $text is our search variable, fwcode is the name of the search box.

Thank you.

The problem is that I need to search in text word strings like: location*code/1334 -> and works but not highlight them if they contains special characters. Also wish if the user enter for search argument only / or * to tell him: nothing found , instead of error.

CodePudding user response:

If your $fwcode variable can contain characters that have special meaning in regular expressions, you must escape $fwcode. The preg_quote function does this.

$fwcode = preg_quote($fwcode,"/");
//.. your preg_replace
  • Related