Code sur écran d'ordinateur

PHP – Protection of special characters of regular expressions

If you want to use a regular expression to, for example, search for a word in a paragraph, it is important to protect your variable. To do this, just use the following function:

string preg_quote ( string $str [, string $delimiter = NULL ] )

For example:

foreach ($aRequest['keywords'] as $sKeyword) {
    $sKeyword = preg_quote($sKeyword);
    $pattern = '/[^a-zA-Z0-9]' . $sKeyword . '[^a-zA-Z0-9]/i';
    preg_match_all($pattern, $sContent, $aResult);
}