up vote 0 down vote favorite

I have a string Action - [N]ew, [U]pdate, or [D]elete : N that I need to replace with "Action - [N]ew, [U]pdate, or [D]elete : U" somhow by using preg_replace I can't get it working. It remains the same.

My code looks like this

$action = Action - '[N]ew, [U]pdate, or [D]elete : U';
$line = preg_replace("/(Action - [N]ew, [U]pdate, or [D]elete : N)/",$action,$line);
flag

4 Answers

up vote 3 down vote accepted

[ and ] are special characters in regular expressions. You'll have to escape them if you want to match them:

"/(Action - \[N\]ew, \[U\]pdate, or \[D\]elete : N)/"

Without being escaped, and expression within [ and ] will match one of every character within them. So in your original case, "[N]ew" was matching "New". If it had been "[NP]ew", it would have matched "New" or "Pew".

link|flag
Thx, this was actually easy, I had to know that, too much coding for a day ;-) – Roland Jul 31 '09 at 15:30
up vote 2 down vote

You don’t need preg_replace to do that. A simple str_replace will suffice:

$action = 'Action - [N]ew, [U]pdate, or [D]elete : U';
$line = str_replace('Action - [N]ew, [U]pdate, or [D]elete : N', $action, $line);
link|flag
+1 for an alternate, simpler solution. I'll let my answer stand in case his example is just a simplification. – Welbog Jul 31 '09 at 15:30
up vote 2 down vote

Couple problems:

1) Syntax error in your first line. Your quotes are misplaced. It should be:

 $action = "Action - [N]ew, [U]pdate, or [D]elete : N";

2) You need to escape the square brackets ([ and ]) in regular expressions. Alternatively, you can do:

 $line = preg_replace("/N$/", "U", $action);

So combining them:

 $action = "Action - [N]ew, [U]pdate, or [D]elete : N";
 $line = preg_replace("/N$/", "U", $action);
link|flag
up vote 0 down vote

try escaping the '[' and ']'

link|flag

Your Answer

get an OpenID
or
never shown

Not the answer you're looking for? Browse other questions tagged or ask your own question.