Matt Altepeter
Matt Altepeter

Reputation: 956

Replace string with regex

I have a string that is a PHP code example that contains the following snippet:

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

Currently I'm just doing a str_replace on two hard-coded keys, but I need this to be more flexible now. These are the two regex I've come up with so far:

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

But, due to some people not using spaces, using double quotes, etc, this is not an ideal solution. Can someone point me in a better way to replace the values of cKey1 and cKey2 in a more efficient way?

Thanks!

Upvotes: 1

Views: 70

Answers (2)

Jan
Jan

Reputation: 43169

Either use the tokenizer like @Casimir said or (if you insist on using a regex), you could come up with sth. like the following:

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

If you want to replace it with sth., consider using preg_replace_callback(), though you were not clear on your expected output.
See a demo on regex101.com. Thanks @WiktorStribiżew for the clarification in the comments.

Upvotes: 1

anubhava
anubhava

Reputation: 784918

You can use \K (match reset feature):

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

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

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

Output:

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

Upvotes: 1

Related Questions