与PHP进行预匹配后如何获得下一个单词。
例如,如果我有这样的字符串:
"This is a string, keyword next, some more text. keyword next-word."
我想使用preg_match
来获取“关键字”之后的下一个单词,包括该单词是否带有连字符。
所以在上述情况下,我想返回“ next”和“ next-word”
我尝试过:
$string = "This is a string, keyword next, some more text. keyword next-word.";
$keywords = preg_split("/(?<=\keyword\s)(\w+)/", $string);
print_r($keywords);
这只是返回所有内容,似乎根本不起作用。
非常感谢您的帮助。
使用您的示例,这应该使用preg_match_all
:
preg_match_all
我得到的结果是:
// Set the test string.
$string = "This is a string, keyword next, some more text. keyword next-word. keyword another_word. Okay, keyword do-rae-mi-fa_so_la.";
// Set the regex.
$regex = '/(?<=\bkeyword\s)(?:[\w-]+)/is';
// Run the regex with preg_match_all.
preg_match_all($regex, $string, $matches);
// Dump the resulst for testing.
echo '<pre>';
print_r($matches);
echo '</pre>';
正向后面寻找的是您想要的:
Array
(
[0] => Array
(
[0] => next
[1] => next-word
[2] => another_word
[3] => do-rae-mi-fa_so_la
)
)
应该与(?<=\bkeyword\s)([a-zA-Z-]+)
完美配合。使用preg_match
修饰符可以捕获所有匹配项。
g
参考问题:Demo
尽管正则表达式功能强大,但对于我们大多数人来说,它也很难调试和记忆。
在这种情况下,在与PHP匹配后得到下一个单词,这是非常常见的字符串操作。
简单地,通过将字符串分解为数组,然后搜索索引。这很有用,因为我们可以指定向前或向后多少个单词。
此匹配项首次出现+ How to match the first word after an expression with regex?:
1 word
<?php
$string = explode(" ","This is a string, keyword next, some more text. keyword next-word.");
echo $string[array_search("keyword",$string) + 1];
/* OUTPUT next, *
通过反转数组,我们可以捕获最后一次出现-Run it online:
1 word
<?php
$string = array_reverse(explode(" ","This is a string, keyword next, some more text. keyword next-word."));
echo $string[array_search("keyword",$string) - 1];
/* OUTPUT next-word. */
如果我们进行多次搜索,这对性能很有好处,但是字符串的长度必须保持短(内存中的整个字符串)。