简单但也不容易。下面是使用preg_match_all
和简单的正则表达式作为一个例子一些代码:
// Set the string.
$string = 'Hereissomerandomsentence';
// Set the words array.
$wordsArray = array('some', 'are', 'the');
// Set the regex pattern.
$regex_pattern = '/(?:' . implode('|', $wordsArray) . ')/i';
// Run a regex to get the value between the link tags.
preg_match_all($regex_pattern, $string, $matches);
// Return the results.
echo '<pre>';
print_r($matches);
echo '</pre>';
,这里是结果:
Array
(
[0] => Array
(
[0] => some
)
)
但是,当我说这是不容易的,缺乏的空间,可能会导致then
与the
等匹配。请记住,电脑无法阅读。这都是模式逻辑。所以,如果我添加then
和are
的例子字符串是这样的:
// Set the string.
$string = 'Hereissomerandomsentencethenhereweare';
结果反映then
的the
被拾起:
Array
(
[0] => Array
(
[0] => some
[1] => the
[2] => are
)
)
编辑:楼主问了一个fair-但在评论中的复杂问题:
如果我只想要一个单词前面有一个单词还是某个单词?对于 例如,使用相同的测试字符串,你怎么能够改变正则表达式 通过 then
前面时is
,the
时之前只包括some
,并通过are
“我们”先当?因此,对于您的示例, 输出将仅为'some'和are
。
你所要求做的是复杂的,但可行使用“Lookarounds” as explained on this site:
下面是一个使用上面的代码示例:
$string = 'Hereissomerandomsentencethenhereweare';
// Set the regex pattern.
$regex_pattern = '/(?<=is)some|(?<=then)the|(?<=we)are/i';
// Run a regex to get the value between the link tags.
preg_match_all($regex_pattern, $string, $matches);
// Return the results.
echo '<pre>';
print_r($matches);
echo '</pre>';
,其结果将是为你期望它:
Array
(
[0] => Array
(
[0] => some
[1] => are
)
)
这里是该正则表达式的说明/(?<=is)some|(?<=then)the|(?<=we)are/i
:
- 开头和结尾的斜线(
/
)只是分隔符。
|
字符是简单的和OR
之间的条件。
- 现在在
OR
条件之间是什么样的模式。
现在让我们以第一个(?<=is)some
为例。
(?<=[word in here])
是一个“Lookbehind”,意思是:只有在这个词前面有这个单词时,才会捕获这个单词。在这种情况下的字是is
。
- 下面的单词是
some
。
- 所以这一切都增加到:只匹配
some
如果前面有is
。然后the
只有前面有then
。然后are
只有前面有we
。
现在知道这里有一个模式可能可能会创建一个多维数组,它可以为单词设置逻辑,以便仅在被另一个单词前面检查时检查。然后循环创建一堆正则表达式。但这是一项重大任务。
但至少现在你知道这个任务的正则表达式的基本知识!
“不需要遍历我的数组字符,而是使用字符串本身,并检查是否在我的数组中找到它的任何子字符串”---为什么你认为'2 + 3'是快于“3 + 2”? – zerkms
可悲的事实是,使用foreach和in_array比使用声明或匿名函数的array_walk快。你到底在做什么?试图找到坏词? – Ohgodwhy
这个问题似乎是离题,因为它是关于改善工作代码,并可能更适合http://CodeReview.stackexchange.com/ –