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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-25 23:48:13  来源:igfitidea点击:

Preg match if not

phpregexpreg-match

提问by fire

Is it possible to do a preg_matchon 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_matchreturn 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 会如何看待一个只有零宽度标记的模式,但我已经在 J​​avaScript 中测试过它并且它工作正常



Edit:

编辑:

If you want to make sure Mozilladoesn'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_matchwill 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 falseis returned from preg_match.

我希望我没有误解你的问题。preg_match将返回 0(未找到)、1(找到 1 个匹配项,不搜索更多)或 false(出现一些问题)。我用===的时候不要返回truefalse从返回preg_match

回答by anubhava

You can use negative lookahead like this:

您可以像这样使用负前瞻:

#^(?!Mozilla)(.*)#