php 如果不是预赛
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6254239/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Preg match if not
提问by fire
Is it possible to do a preg_match
on something that shouldn't be a match whilst still returning true?
是否有可能在不preg_match
应该匹配的同时仍然返回 true 的东西上做一个?
For example at the moment we have...
例如目前我们有...
if (preg_match('#^Mozilla(.*)#', $agent)) {
We want to check if the Mozilla string is not in $agent but still have preg_match
return true.
我们想检查 Mozilla 字符串是否不在 $agent 中但仍然preg_match
返回 true。
So we can't change it to...
所以我们不能把它改成...
if (!preg_match('#^Mozilla(.*)#', $agent)) {
Thanks
谢谢
回答by Justin Morgan
What you want is a negative lookahead, and the syntax is:
你想要的是一个负面的lookahead,语法是:
if (preg_match('#^(?!Mozilla).#', $agent)) {
Actually, you can probably get away with just #^(?!Mozilla)#
for this. I don't know how PHP will feel about a pattern that's nothing but zero-width tokens, but I've tested it in JavaScript and it works fine.
实际上,您可能只是#^(?!Mozilla)#
为此而逃脱。我不知道 PHP 会如何看待一个只有零宽度标记的模式,但我已经在 JavaScript 中测试过它并且它工作正常。
Edit:
编辑:
If you want to make sure Mozilla
doesn't appear anywherein the string, you could use this...
如果你想确保Mozilla
没有出现在字符串中的任何地方,你可以使用这个...
if (preg_match('#^((?!Mozilla).)*$#', $agent)) {
...but only if you can't use this!
...但前提是你不能使用它!
if (strpos($agent, 'Mozilla') !== false) {
回答by kapa
if (preg_match('#^Mozilla(.*)#', $agent) === 0) {
I hope I have not misunderstood your question. preg_match
will either return 0 (not found), 1 (found 1 match, does not search for more), or false (some problem occurred). I used ===
not to return true when false
is returned from preg_match
.
我希望我没有误解你的问题。preg_match
将返回 0(未找到)、1(找到 1 个匹配项,不搜索更多)或 false(出现一些问题)。我用===
的时候不要返回truefalse
从返回preg_match
。
回答by anubhava
You can use negative lookahead like this:
您可以像这样使用负前瞻:
#^(?!Mozilla)(.*)#