简体   繁体   中英

How can use a match in the same regex in php?

I have this string (that is a serialized variable in php):

s:12:"hello "world";

and I wanna to find "hello "world" only with regex, I try this, but seems it is stupid :P

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

I only want to know how I can use "num" result in the its regex?

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'. Additionally PHP 5.2.4 added support for \\k{name} and \\g{name}.

According to 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:

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.

More information about 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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