2013-07-26 28 views
0

字符串解析:提高預浸料/ PCRE /正則表達式來找到PHP變量

$str = " 
public $xxxx123; 
private $_priv ; 
     $xxx  = 'test'; 
private $arr_123 = array(); 
"; // |  | 
    //  ^^^^^^^---- get the variable name 

我有什麼至今:

$str = preg_match_all('/\$\S+(;|[[:space:]])/', $str, $matches); 
    foreach ($matches[0] as $match) { 
     $match = str_replace('$', '', $match); 
     $match = str_replace(';', '', $match); 
    } 

它的工作原理,但我想,如果我能知道改進preg,例如干掉兩個str_replace的,也許包括\t(;|[[:space:]])

回答

4

使用正回顧後,你可以得到,你需要什麼,相信你一定會只匹配有效變量名,我用這個:

preg_match_all('/(?<=\$)[a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*/',$str,$matches); 
var_dump($matches); 

其正確地顯示:

 
array (
    0 => 
    array (
    0 => 'xxxx123', 
    1 => '_priv', 
    2 => 'xxx', 
    3 => 'arr_123' 
) 
) 

這就是你所需要的,沒有內存在包含所有變量及其前導和/或尾隨字符的數組上。

表達:

  • (?<=\$)是一種積極的回顧後
  • [a-zA-Z_\x7f-\xff][a-zA-Z0-9_\x7f-\xff]*:是PHP的網站上介紹自己的正則表達式on their document pages
+0

有效的PHP var名稱的正則表達式,這也會匹配其他隨機字符串像$(「=§/&=」§/ $),它也不會正確地匹配像$ x = 123; –

+0

這樣的東西,例如在這裏「!」§$%&/()=?'「 - > $%&/() –

+0

好了現在我們接近一些很好的解決方案:D –

1

只需使用反向引用

preg_match_all('/\$(\S+?)[;\s=]/', $str, $matches); 
foreach ($matches[1] as $match) { 

    // $match is now only the name of the variable without $ and ; 
} 
1

我改變了正則表達式一點點,一起來看看:

$str = ' 
public $xxxx123; 
private $_priv ; 
     $xxx  = "test"; 
private $arr_123 = array(); 
'; 

$matches = array(); 

//$str = preg_match_all('/\$(\S+)[; ]/', $str, $matches); 
$str = preg_match_all('/\$(\S+?)(?:[=;]|\s+)/', $str, $matches); //credits for mr. @booobs for this regex 

print_r($matches); 

輸出:

Array 
(
    [0] => Array 
     (
      [0] => $xxxx123; 
      [1] => $_priv 
      [2] => $xxx 
      [3] => $arr_123 
     ) 

    [1] => Array 
     (
      [0] => xxxx123 
      [1] => _priv 
      [2] => xxx 
      [3] => arr_123 
     ) 

) 

現在您可以使用$matches[1]在foreach循環中。

::更新::

使用正則表達式「後/ \ $([A-ZA-Z_ \ x7f- \ XFF] [A-ZA-Z0-9_ \ x7f- \ XFF] *)/ 「輸出看起來正確。

字符串:

$str = ' 
public $xxxx123; $input1;$input3 
private $_priv ; 
     $xxx  = "test"; 
private $arr_123 = array(); 

「;

和輸出:

Array 
(
    [0] => Array 
     (
      [0] => $xxxx123 
      [1] => $input1 
      [2] => $input3 
      [3] => $_priv 
      [4] => $xxx 
      [5] => $arr_123 
     ) 

    [1] => Array 
     (
      [0] => xxxx123 
      [1] => input1 
      [2] => input3 
      [3] => _priv 
      [4] => xxx 
      [5] => arr_123 
     ) 

) 
+0

我會改變的正則表達式更使得它即使匹配在賦值操作符之前沒有空格:'\ $(\ S +?)(?:[=;] | \ s +)' – nstCactus

+0

問題在這裏:'$ input; $ input2;'它不匹配'$ input2;' – DanFromGermany

+0

@sbooob不錯,我會改變正則表達式。 – Benz