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 を改善できるかどうか知りたいです。たとえば、2つを取り除き、str_replaceおそらくに\t含める(;|[[:space:]])

4

3 に答える 3

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 に答える