简体   繁体   English

如何在PHP的同一个正则表达式中使用匹配项?

[英]How can use a match in the same regex in php?

I have this string (that is a serialized variable in php): 我有这个字符串(这是php中的序列化变量):

s:12:"hello "world";

and I wanna to find "hello "world" only with regex, I try this, but seems it is stupid :P 我想只用正则表达式来找到“ hello”世界,我尝试了一下,但是看起来很愚蠢:P

(s:(?P<num>[0-9]+):".{\k{num}}";)

I only want to know how I can use "num" result in the its regex? 我只想知道如何在其正则表达式中使用“ num”结果?

this regex is used in a big regex so I can't check for end of string. 这个正则表达式用在一个大的正则表达式中,所以我不能检查字符串的结尾。

thanks advance! 谢谢提前!

You can use your named capturing groups as backreference like this 您可以像这样将命名的捕获组用作反向引用

Back references to the named subpatterns can be achieved by (?P=name) or, since PHP 5.2.2, also by \\k or \\k'name'. 通过(?P = name)或自PHP 5.2.2起,也可以通过\\ k或\\ k'name'实现对已命名子模式的反向引用。 Additionally PHP 5.2.4 added support for \\k{name} and \\g{name}. 另外,PHP 5.2.4添加了对\\ k {name}和\\ g {name}的支持。

According to php.net 根据php.net

But I think this can be used only to match the found pattern again, but not as a number in a quantifier. 但是我认为这只能用于再次匹配找到的模式,而不能用作量词中的数字。 (At least I didn't got it to work.) (至少我没有使其工作。)

You can use preg_match function, which will populate an array of matches: 您可以使用preg_match函数,该函数将填充匹配项数组:

If matches is provided, then it is filled with the results of search. 如果提供了匹配项,则将其填充为搜索结果。 $matches[0] will contain the text that matched the full pattern, $matches 1 will have the text that matched the first captured parenthesized subpattern, and so on. $ matches [0]将包含与完整模式匹配的文本,$ matches 1将具有与第一个捕获的带括号的子模式匹配的文本,依此类推。

More information about preg_match: PHP: preg_match 有关preg_match的更多信息: PHP:preg_match

$text = 's:12:"hello "world";s:12:"good bue world";';
    $pattern = "(.*:[0-9]+:\"(.*)\";.*)U";
    preg_match_all($pattern,$text,$r);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM