用正则表达式替换字符串

时间:2016-02-25 17:06:38

标签: php regex

我有一个字符串,它是一个PHP代码示例,其中包含以下代码段:

$data = array(
    'cKey1' => "dsfaasdfasdfasdfasdf",
    'cKey2' => "asdfasdfasdfadsfasdf",
    ...
);

目前,我只是在两个硬编码密钥上执行str_replace,但我现在需要更灵活。这是我到目前为止提出的两个正则表达式:

(?<=cKey1' => ).+(?=,)
(?<=cKey2' => ).+(?=,)

但是,由于有些人不使用空格,使用双引号等,这不是一个理想的解决方案。有人可以用更好的方式指出我以更有效的方式替换cKey1cKey2的值吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

要么像@Casimir那样使用标记器,要么(如果你坚持使用正则表达式),你可以拿出来......如下:

$regex = "~
            'cKey\d+'           # search for cKey followed by a digit
            .+?                 # match everything lazily
            ([\"'])             # up to a single/double quote (capture this)
            (?P<string>.*?)     # match everything up to $1
            \1                  # followed by the previously captured group
        ~x";
preg_match_all($regex, $your_string, $matches);

如果您想用某物替换它,请考虑使用preg_replace_callback(),但您不清楚预期的输出。
a demo on regex101.com。感谢@WiktorStribiżew在评论中做出澄清。

答案 1 :(得分:1)

您可以使用\K(匹配重置功能):

$re = array("/'cKey1'\s*=>\s*\K[^,]*/", "/'cKey2'\s*=>\s*\K[^,]*/");

$repl = array('"foo"', '"bar"')

echo preg_replace($re, $repl, $str);

<强>输出:

$data = array(
    'cKey1' => "foo",
    'cKey2' => "bar",
    ...
);
相关问题