2012-06-11 65 views
1

多次出現我有以下字符串:正則表達式PHP的preg_match字符串

findByHouseByStreetByPlain

我如何能匹配值後,每個 「通過」。我已經設法找到第一個「By」的價值,但我無法得到它,它給了我「After」之後的值的所有匹配。

+1

顯示你已經嘗試過的情況。 – flowfree

回答

3

Thsi正則表達式應該爲你工作:

<?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 
     ) 

) 
+0

可以工作但請記住,只有在字符串以大寫字母開頭,後面跟着小寫字母。例如,findByHouSeByStreet將不匹配 – buckley

+0

嗯,這是它應該是怎樣的駱駝情況下被寫入。對於更復雜的例子.. – SERPRO

+0

我解釋爲分隔符是「通過」 – buckley

0

試試下面這段代碼:

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

它也與「查找」匹配。 – flowfree

+1

並且也會因'findByByte'失敗(例如) – SERPRO

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]; 
    } 
} 
+0

該正則表達式返回前綴爲By的字符串.. – SERPRO

+0

如果要提取子匹配,只需添加一些分組 – buckley

0

我的字符串是不同的:

HouseByStreetByPlain

然後我用下面的正則表達式:

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

輸出:

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

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

)