php 多个单词的 preg_match

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9689521/
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-26 07:25:44  来源:igfitidea点击:

preg_match for multiple words

php

提问by Asim Zaidi

I want to test a string to see it contains certain words.

我想测试一个字符串以查看它包含某些单词。

i.e:

IE:

$string = "The rain in spain is certain as the dry on the plain is over and it is not clear";
preg_match('`\brain\b`',$string);

But that method only matches one word. How do I check for multiple words?

但是这种方法只匹配一个词。如何检查多个单词?

回答by jeroen

Something like:

就像是:

preg_match_all('#\b(rain|dry|clear)\b#', $string, $matches);

回答by Czechnology

preg_match('~\b(rain|dry|certain|clear)\b~i',$string);

You can use the pipe character (|) as an "or" in a regex.

您可以将管道字符 ( |) 用作正则表达式中的“或”。

If you just need to know if any of the words is present, use preg_matchas above. If you need to match all the occurences of any of the words, use preg_match_all:

如果您只需要知道是否存在任何单词,请使用preg_match如上。如果您需要匹配任何单词的所有出现,请使用preg_match_all

preg_match_all('~\b(rain|dry|certain|clear)\b~i', $string, $matches);

Then check the $matchesvariable.

然后检查$matches变量。

回答by Pave

http://php.net/manual/en/function.preg-match.php

http://php.net/manual/en/function.preg-match.php

"Do not use preg_match() if you only want to check if one string is contained in another string. Use strpos() or strstr() instead as they will be faster."

“如果您只想检查一个字符串是否包含在另一个字符串中,请不要使用 preg_match()。改用 strpos() 或 strstr(),因为它们会更快。”

回答by cetver

preg_match('\brain\b',$string, $matches);
var_dump($matches);