PHP preg_match and preg_quote do not match the dollar sign

综合编程 2018-05-26

I'm trying to scan a string to check against a blacklist of words. I've used preg_quote
to handle special characters such as an asterisk but it doesn't seem to work for the dollar sign.

Here is a test I've been running:

$string_to_check = 'wordcontaining$';
$naughty_words = array('wordcontaining$', 'a*differentstring');
if(isset($naughty_words)){
    foreach($naughty_words as $word){
        if (preg_match('/b'.preg_quote($word).'b/i',$string_to_check)) {
            var_export(array('found'=> true, 'word'=>$word));
        }
    }
}

which I would expect to return

array (
    'found' => true,
    'word' => 'wordcontaining$',
)

but unfortunately it's not. If I set $string_to_check = 'a*differentstring'
then everything works as expected.

Have I missed something very obvious here?

b matches a position between a w (word) and a W (non-word)

w is the same as [a-zA-Z0-9_] so $ and space are both non-word, so if the 'naughty_word' starts or ends with a symbol your expression can't match

you have to use something like

preg_match('/s*+'.preg_quote($word).'s*+/i',$string_to_check)

您可能感兴趣的

Added the module name to the application&perio... I am newbie to zend framework and i am trying to configure the zend.. In that process i created some album module.. by following the Zend user-guid...
PHP高级面试题汇总 一、PHP核心技术 1.写出一个能创建多级目录的PHP函数(新浪网技术部) 2.写出smarty模板的特点(新浪网技术部) 速度快,编译型,缓存技术,插件机制,强大的表现逻辑 3.打开php.ini中的safe_mode,会影响哪些函数?至少说出6个。(新浪)saf...
HTML Table Listing Using PHP and PostgreSQL Databa... This PHP tutorial help to create HTML listing using PostgreSQL database.Its very simple and easy to create HTML listing using PHP, as like other datab...
Preg_replace pattern for php I got some problems with my patterns. Hope somebody could help me with this. given a string $string = Mutualism has been retrospectively character...
March Madness brackets in PHP (scores) To get ready for this year's March Madness, I updated my Bash script that filled out basketball game brackets. The new version is a PHP page that ...