正则表达式php preg_match在字符串中多次出现

时间:2012-06-11 12:26:30

标签: php regex preg-match

我有以下字符串:

  

findByHouseByStreetByPlain

如何在每个“By”之后匹配值。我已经设法找到了第一个“By”值,但是我无法理解它在“By”之后给了我所有匹配值。

4 个答案:

答案 0 :(得分:3)

Thhe正则表达式适合你:

<?php 
$ptn = "#(?:By([A-Za-z]+?))(?=By|$)#";
$str = "findByByteByHouseNumber";
preg_match_all($ptn, $str, $matches, PREG_PATTERN_ORDER);
print_r($matches);
?>

这将是输出:

Array
(
    [0] => Array
        (
            [0] => ByByte
            [1] => ByHouseNumber
        )

    [1] => Array
        (
            [0] => Byte
            [1] => HouseNumber
        )

)

答案 1 :(得分:1)

使用前瞻会做到这一点

By(.*?)(?=By|$)

在php中,这就变成了

preg_match_all('/By(.*?)(?=By|$)/', $subject, $result, PREG_SET_ORDER);
for ($matchi = 0; $matchi < count($result); $matchi++) {
    for ($backrefi = 0; $backrefi < count($result[$matchi]); $backrefi++) {
        # Matched text = $result[$matchi][$backrefi];
    } 
}

答案 2 :(得分:0)

请尝试以下代码:

$pattern = "/[^By]+/";
$string = "findByHouseByStreetByPlain";
preg_match_all($pattern, $string, $matches);
var_dump($matches);

答案 3 :(得分:0)

我的字符串不同:

  

HouseByStreetByPlain

然后我使用以下正则表达式:

this.set('data.active', !this.data.active);

输出:

<?php 
$ptn = "/(?<=By|^)(?:.+?)(?=(By|$))/i";
$str = "HouseByStreetByPlain";
preg_match_all($ptn, $str, $matches);
print_r($matches);
?>