简体   繁体   English

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

[英]Regex php preg_match multiple occurrences in string

I have the following string: 我有以下字符串:

findByHouseByStreetByPlain findByHouseByStreetByPlain

How can I match to values after each "By". 如何在每个“By”之后匹配值。 I have managed to find the first "By" value, but I can't get it going that it gives me all the matches for the value after "By". 我已经设法找到第一个“By”值,但是我无法理解它给了我“By”之后的值的所有匹配。

Thsi regex should work for you: Thsi正则表达式应该适合你:

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

this will be the output: 这将是输出:

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

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

)

Some use of lookahead will do it 使用前瞻可以做到这一点

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

In php this become 在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];
    } 
}

Try this code below: 请尝试以下代码:

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

my string is different: 我的字符串是不同的:

HouseByStreetByPlain HouseByStreetByPlain

then i use the following regex: 然后我使用以下正则表达式:

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

output: 输出:

Array
(
    [0] => Array
        (
            [0] => House
            [1] => Street
            [2] => Plain
        )

    [1] => Array
        (
            [0] => By
            [1] => By
            [2] => 
        )

)

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

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