簡體   English   中英

改進preg / pcre / regex以查找PHP變量

[英]improve preg / pcre / regex to find PHP variable

要解析的字符串:

$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);
     }

它有效,但是我想知道我是否可以改善預浸料坯 ,例如擺脫兩個str_replace並在(;|[[:space:]])加入\\t

使用正回顧后,你只能得到你需要什么,相信你一定會只匹配有效的變量名,我用這個:

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的網站在其文檔頁面上建議自己

只需使用反向引用

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

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

我稍微修改了正則表達式,看看:

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

)

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

::更新::

使用正則表達式“ / \\ $([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
        )

)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM