Jules
Jules

Reputation: 7776

PHP, Error preg_match_all error unknown modifier?

I'm getting the following error

[13-Sep-2011 07:26:28] PHP Warning:  preg_match_all() [<a 
href='function.preg-match-all'>function.preg-match-all</a>]: Unknown 
modifier 'w' in D:\domains\wwwroot\php\search.php on line 274

The value of search is "repair a pst"

$text1 = $result['ProgramName'] . " " . $result['ProgramVersion'];
$keywords1 = explode(" ",stripslashes($search));
foreach ($keywords1 as $k){
    preg_match_all("/$k/i",$text1,$matches);
    foreach ($matches[0] as $m){
    $text1 = preg_replace("/$m/", '<span class="highlight">'.$m.'</span>', $text1);
    }
}

I'm really quite puzzled what the problem is ?

Upvotes: 0

Views: 925

Answers (3)

Marc B
Marc B

Reputation: 360762

You're creating arbitrary regex strings by inserting whatever $k happens to be at the time. If $k contains any regex metacharacters, you'll end up with the regex equivalent of sql injection attacks. You need to use preg_quote() to sanitize $k:

preg_match_all("/" . preg_quote($k) . "/i", $text1, $matches);'

Upvotes: 1

Tim Pietzcker
Tim Pietzcker

Reputation: 336378

One of the keywords contains a slash.

This causes your regex to be terminated prematurely (at that slash) and the following character (in this case w) is interpreted as an invalid modifier.

Solution: Call preg_quote() on your keywords before adding them into the regex.

Upvotes: 0

genesis
genesis

Reputation: 50974

$k or $m includes /w probably. You have to escape them

$m = str_replace('/', '\\/', $m);
$k = str_replace('/', '\\/', $k);

Upvotes: 1

Related Questions