Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/266.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用PHP在preg匹配后获取下一个单词_Php_Preg Match - Fatal编程技术网

使用PHP在preg匹配后获取下一个单词

使用PHP在preg匹配后获取下一个单词,php,preg-match,Php,Preg Match,如何在与PHP进行预匹配后获得下一个单词 例如,如果我有这样一个字符串: "This is a string, keyword next, some more text. keyword next-word." 我想使用preg_匹配来获取“keyword”之后的下一个单词,包括该单词是否连字符 在上面的例子中,我想返回“next”和“next word” 我试过: $string = "This is a string, keyword next, some more text. keywo

如何在与PHP进行预匹配后获得下一个单词

例如,如果我有这样一个字符串:

"This is a string, keyword next, some more text. keyword next-word."
我想使用preg_匹配来获取“keyword”之后的下一个单词,包括该单词是否连字符

在上面的例子中,我想返回“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);
它只是返回所有东西,似乎根本不起作用


非常感谢您的帮助。

以您的示例为例,这应该可以通过以下方式实现:


积极的回头看是你想要的:

<?php
$string = explode(" ","This is a string, keyword next, some more text. keyword next-word.");
echo $string[array_search("keyword",$string) + 1];
/* OUTPUT next, *
应该与preg_match完美配合。使用g修改器捕捉所有匹配项


参考问题:

尽管正则表达式功能强大,但对我们大多数人来说,它也很难调试和记忆

在这个特殊的案例中,请在。。。匹配PHP,这是一个非常常见的字符串操作

简单地说,在数组中分解字符串并搜索索引。这很有用,因为我们可以指定向前或向后的单词数量

这与第一次出现的+1个单词匹配:


如果我们进行多次搜索,这有助于提高性能,但当然字符串的长度必须短于内存中的整个字符串。

strpos提供了显示内容的位置,并使您可以轻松地找到后面的点。strpos只返回第一次出现的内容。我想把所有事情都推到一个合理的高度。我的正则表达式经验不知道@JeremyMiller FWIW,那?“使用g修饰符捕捉所有匹配项。”你是说i修饰符不区分大小写,对吗?那么为什么不使用/?@JakeGould 1:/?@JakeGould仍然我对你的答案投了赞成票,因为它更详细。并为询问者服务:谢谢你的更正。请停止接受建设性的批评,这些批评可能是错误的,但被要求是真诚的,所以是个人的,反应是“老兄”。好吗?哇,太好了!非常感谢您的帮助:@user3143218谢谢!我只是让它变得更好!您可以从字符类、非捕获组和s修饰符中删除uu。@casimirithippolyte我特意添加了uuu,以显示如何使用不同的非字母字符。但只是在没有u的情况下尝试了一下,效果如何?为什么?如果我删除-测试失败,只有一个半字?很好,我做了preg_match而不是preg_match_all,并使用echo$matches{0]显示$regex='/'后面的第一个字?
Array
(
    [0] => Array
        (
            [0] => next
            [1] => next-word
            [2] => another_word
            [3] => do-rae-mi-fa_so_la
        )

)
(?<=\bkeyword\s)([a-zA-Z-]+)
<?php
$string = explode(" ","This is a string, keyword next, some more text. keyword next-word.");
echo $string[array_search("keyword",$string) + 1];
/* OUTPUT next, *
<?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. */