开发者

Is there a function in PHP that uses Regex and returns an array of results?

preg_match returns only the first result.

lets say I have the string abcabcabc and I wa开发者_StackOverflow中文版nna find ALL indexes of ABC. (ofcourse mine is a bit more complex...) - how can I do it ?

Thank you!


preg_match_all

You simply have to pass in a variable as the third argument that will be loaded up with all your matches.

Example

<?php
$pattern = "/{[^}]*}/";
$subject = "{token1} foo {token2} bar";
preg_match_all($pattern, $subject, $matches);
print_r($matches);
?>

output:

Array
(
    [0] => Array
        (
            [0] => {token1}
            [1] => {token2}
        )

)


preg_match_all does not suite you? preg_match_all


preg_match_all( $pattern, $subject, $matches )

Used like this preg_match_all returns an int but populates the $matches array.
Look here for function documentation.
Your example can be solved like this:

$subject = "abcabcabc";
$pattern = "/abc/";
if( preg_match_all( $pattern, $subject, $matches ) ) {
    print_r($matches);
} else {
    echo "No match.";
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜