How to use php regular expression not to contain a certain string: first create a PHP sample file; then use the regular expression "preg_match("/[^(abc)]/s", $str, $arr); "Just implement the judgment that it does not contain a certain string.
Recommended: "PHP Video Tutorial"
Common functions strstr($str, "abc" );
Regular matching preg_match(”/(abc)?/is”, $str);
But if you want to match a string that does not contain a certain string, it is more troublesome to use regular matching
If The problem can be solved without using the regular expression !strstr($str, “abc”);
But with the regular expression, there is only this, “/^((?!abc).)*$/is”
//------------------------------------------------ 代码如下: <?php $str = "dfadfadf765577abc55fd"; $pattern_url = "/^((?!abc).)*$/is"; if (preg_match($pattern_url, $str)){ echo "不含有abc!"; }else{ echo "含有abc!"; } ?> //------------------------------------------------ 结果为:false,含有abc! $str = “2b3c4d5c”; 注意:[^(abc)] 这个语法是逐个检查$str中的字符是否不在 a b c中, preg_match(”/[^(abc)]/s”, $str, $arr); 其中字符 2 就不在 a b c 中,所以$arr返回值为2; 同时匹配,包含字符串 “abc”,而且不包含字符串 “xyz” “/(abc)[^((?!xyz).)*$]/s”
The following is a supplement:
There are many methods to determine whether a string contains another string, as follows:
1. Common Function
strstr($str, "abc");
2. Regular matching
preg_match("/(abc)/is", $str);
But if you want to match a string that does not contain a certain string, it is more troublesome to use regular matching.
1. If you don’t use regular expressions, you can solve the problem as follows
!strstr($str, "abc");
2. But with regular expressions, that’s all.
preg_match("/^((?!abc).)*$/is", $str);
Complete code example
The code is as follows:
$str = "dfadfadf765577abc55fd"; $pattern_url = "/^((?!abc).)*$/is"; if (preg_match($pattern_url, $str)) { echo "不含有abc!"; } else { echo "含有abc!"; }
The result is: false, containing abc!
Match at the same time, the regular expression that contains the string "abc" and does not contain the string "xyz":
preg_match("/(abc)[^((?!xyz) .)*$]/is", $str);
This method is effective. I use it as follows:
(?:(?!<\/p>).|\n)*? //匹配不含</p>的一个字符串
But in the end, it was found that this method is extremely inefficient. You can consider using it when processing very short text (there are a dozen words, or at most dozens of words, that need to match the same part of the regular expression), but you should not use it when parsing a large article or when you need to change the matching time in multiple places. , consider using other methods instead (such as: first parse out the text to match the regular expression, and then verify whether a certain text exists in it), regular expressions are not very effective for matching text fields that do not contain specific strings. method.
The above is the detailed content of How to exclude a certain string in php regular expression. For more information, please follow other related articles on the PHP Chinese website!