php regex从JS代码中获取字符串

时间:2016-07-16 22:57:43

标签: php preg-match preg-match-all

输入是:

arrCur['AZN'] = 1;
arrCur['AZN'] = 1;
arrCur['USD'] = 1.545;
arrCur['USD'] = 1.57;
arrCur['EUR'] = 1.72;
arrCur['EUR'] = 1.745;
arrCur['GBP'] = 2.02;
arrCur['GBP'] = 2.1753;
arrCur['RUR'] = 0.02381;
arrCur['RUR'] = 0.025;
arrCur['TRY'] = 0.5095;
arrCur['TRY'] = 0.5519;

我想获得货币代码和费率。我的代码是:

if(preg_match_all('/arrCur[\'(.*?)\'] \= (.*?)\;/mis', $get, $arrcur))
{
    print_r($arrcur);
    die;
}

但它不起作用。我的错误在哪里?

2 个答案:

答案 0 :(得分:2)

您需要转义方括号,因为它们在正则表达式中具有特殊含义。

您还不必要地转义=;,因此您可以删除这些反斜杠。如果使用双引号,则可以避免转义表达式中的单引号。这是一个固定版本:

$get = <<<END
arrCur['AZN'] = 1;
arrCur['AZN'] = 1;
arrCur['USD'] = 1.545;
arrCur['USD'] = 1.57;
arrCur['EUR'] = 1.72;
arrCur['EUR'] = 1.745;
arrCur['GBP'] = 2.02;
arrCur['GBP'] = 2.1753;
arrCur['RUR'] = 0.02381;
arrCur['RUR'] = 0.025;
arrCur['TRY'] = 0.5095;
arrCur['TRY'] = 0.5519;
END;

$arrcur = [];
if(preg_match_all("/arrCur\['(.*?)'\] = (.*?);/mis", $get, $arrcur))
{
    print_r($arrcur);
    die;
}

输出:

Array
(
    [0] => Array
        (
            [0] => arrCur['AZN'] = 1;
            [1] => arrCur['AZN'] = 1;
            [2] => arrCur['USD'] = 1.545;
            [3] => arrCur['USD'] = 1.57;
            [4] => arrCur['EUR'] = 1.72;
            [5] => arrCur['EUR'] = 1.745;
            [6] => arrCur['GBP'] = 2.02;
            [7] => arrCur['GBP'] = 2.1753;
            [8] => arrCur['RUR'] = 0.02381;
            [9] => arrCur['RUR'] = 0.025;
            [10] => arrCur['TRY'] = 0.5095;
            [11] => arrCur['TRY'] = 0.5519;
        )

    [1] => Array
        (
            [0] => AZN
            [1] => AZN
            [2] => USD
            [3] => USD
            [4] => EUR
            [5] => EUR
            [6] => GBP
            [7] => GBP
            [8] => RUR
            [9] => RUR
            [10] => TRY
            [11] => TRY
        )

    [2] => Array
        (
            [0] => 1
            [1] => 1
            [2] => 1.545
            [3] => 1.57
            [4] => 1.72
            [5] => 1.745
            [6] => 2.02
            [7] => 2.1753
            [8] => 0.02381
            [9] => 0.025
            [10] => 0.5095
            [11] => 0.5519
        )

)

答案 1 :(得分:0)

疑难杂症!

if(preg_match_all('/arrCur\[\'(.*?)\'\] \= (.*?)\;/mis', $get, $arrcur))
{
    print_r($arrcur);
    die;
}