Chris Pink
Chris Pink

Reputation: 2027

Regular expressions in search and replace

I have inherited a couple of thousand lines of code with every array key string value missing its quote marks, for example [input] should read ['input'] otherwise my PHP (rightly) throws a right hissy fit when debugging.

I am trying a regular expression search and replace, I can find the parts OK, for instance \[([a-z])\w+\] will find [input] and ignore ['preview']

But I can't work out how to do the replace.

Could someone help please?

Upvotes: 1

Views: 66

Answers (2)

Federico Piazza
Federico Piazza

Reputation: 30985

You can use a regex like this:

\[(\w+)\]

With a replacement

['$1']

Working demo

Php code

$re = "/\\[(\\w+)\\]/"; 
$str = "[key]\n[key2]\n[key_asdf]"; 
$subst = "['$1']"; 

$result = preg_replace($re, $subst, $str);

Upvotes: 2

OnlineCop
OnlineCop

Reputation: 4069

Do you mean like this?

\[([^'\]]+)\]

Replaced with

['\1']

If it looks good, you can use code generator on the left to see the PHP regex code.

Upvotes: 2

Related Questions