0

I want to replace some strings by other one. I use below codes:

$mc = 'Hello I have these bages: [A-561],[A-123],[A-1],[A-5234]';
$medal = '<img src="1" />';
$bages = preg_replace('/^\[A-[0-9]+\]/i',$medal,$mc);
echo $bages

it prints out this:

Hello I have these bages: [A-561],[A-123],[A-1],[A-5234]

and if i change $mc to

$mc = "[A-561],[A-123],[A-1],[A-5234]";

then prints out:

<img src="1" />,[A-123],[A-1],[A-5234]

I have no idea why it happens like this. i want to change all of them to my replace string.

  • You have an `^` in your regex. Do you know what it means? * See also [Open source RegexBuddy alternatives](http://stackoverflow.com/questions/89718/is-there) and [Online regex testing](http://stackoverflow.com/questions/32282/regex-testing) for some helpful tools, or [RegExp.info](http://regular-expressions.info/) for a nicer tutorial. – mario Oct 23 '12 at 20:21

1 Answers1

3

The ^ in your regex makes the regex only match on the start of a string.

Remove that ^ from the regex:

$bages = preg_replace('/\[A-[0-9]+\]/i',$medal,$mc);
Khôi
  • 2,133
  • 11
  • 10