PHP - preg_match - How to match a string upper/lower case with anything before or after it?

丶灬走出姿态 提交于 2019-12-07 15:08:21

问题


I have a part of a function that goes like this:

if (preg_match("#\bscript\b#",$userInput))
{
    $bannedWord = 'script';
    logHax();
    return TRUE;
}

This is causing a problem for what I am trying to accomplish because it will only match the exact word "script" and not variations of it, like "ScriPt" or "<script>".

What I would like to have is the examples of the not matched strings along with the original string return true.

Could someone provide me with a bit of understanding on this matter.

Also any tutorials that cover something like this would be greatly appreciated,

Thank you!


回答1:


How's this:

if (preg_match("/<script\b[^>]*>/i",$userInput))
{
    $bannedWord = 'script';
    logHax();
    return TRUE;
}



回答2:


Case-insensitive matching:

preg_match("#\bscript\b#i",$userInput)

Note the i. Also note that this the first example in the docs:

<?php
// The "i" after the pattern delimiter indicates a case-insensitive search
if (preg_match("/php/i", "PHP is the web scripting language of choice.")) {
    echo "A match was found.";
} else {
    echo "A match was not found.";
}
?>

Cheers




回答3:


If you really want to match "anything" before or after the string (not just a word), then you do not even need preg_match here, bacuse you could do something like this:

$userInputLower = strtolower($userInput);
if (strpos($userInputLower, 'script') !== false)
{
    $bannedWord = 'script';
    logHax();
    return TRUE;
}


来源:https://stackoverflow.com/questions/10148297/php-preg-match-how-to-match-a-string-upper-lower-case-with-anything-before-o

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!