0

要解析的字符串:

$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

3 回答 3

4

使用积极的向后看,你只能得到需要的东西,以确保你只会匹配有效的变量名,我使用了这个:

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

正确显示:

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

这就是您所需要的,在包含所有变量及其前导和/或尾随字符的数组上没有内存。

表达方式:

于 2013-07-26T07:40:53.843 回答
1

只需使用反向引用

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

     // $match is now only the name of the variable without $ and ;
}
于 2013-07-26T07:35:18.797 回答
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
        )

)
于 2013-07-26T07:35:32.757 回答