preg_match 多个单词

问题描述 投票:0回答:4

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

即:

$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);

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

php regex string-matching cpu-word word-boundaries
4个回答
28
投票

霍雷肖

The same, my lord, and your poor servant ever.

哈姆雷特

Sir, my good friend; I'll change that name with you:
And what make you from Wittenberg, Horatio? Marcellus?

马塞勒斯

My good lord--

哈姆雷特

I am very glad to see you. Good even, sir.
But what, in faith, make you from Wittenberg?

霍雷肖

A truant disposition, good my lord.

哈姆雷特

I would not hear your enemy say so,
Nor shall you do mine ear that violence,
To make it truster of your own report
Against yourself: I know you are no truant.
But what is your affair in Elsinore?
We'll teach you to drink deep ere you depart.

霍雷肖

My lord, I came to see your father's funeral.

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

您可以在正则表达式中使用管道字符 (

|
) 作为“或”。

如果您只需要知道是否存在任何单词,请使用上面的

preg_match
。如果您需要匹配任何单词的所有出现,请使用
preg_match_all
:

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

然后检查

$matches
变量。


2
投票

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

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


1
投票
preg_match('\brain\b',$string, $matches);
var_dump($matches);
© www.soinside.com 2019 - 2024. All rights reserved.