K. Kirkov K. Kirkov - 3 months ago 19
PHP Question

Preg_replace content with id

I have the following subject:

$subject = '[ta #12286152] c-d0-231-34 drop [#3414a43]';


I want to match everything that have given id. My code is this but when put,
12286152
it is replaced okay, but when put
3414a43
, all subject was removed?

echo preg_replace('/(\[)(.*?)3414a43(.*?)(\])/', '', $subject);


I want to replace all in
[]
that have MY id.

Answer

The whole subject got removed because the first [ matched was the [ next to ta, and .*? matched until the first 3414a43. See your regex demo.

You need to use negated character class [^][] or [^]]:

/\[[^][]*3414a43[^][]*]/

See the regex demo

Pattern details:

  • \[ - a literal [
  • [^][]* - zero or more chars other than [ and ] ([^]]* will match 0+ non-]s)
  • 3414a43 - your ID
  • [^][]* - ibid.
  • ] - a literal closing ] symbol (no need escaping it outside a character class)

Since you are not using captures, I suggest removing all the capturing group parentheses.

PHP demo:

$id = "3414a43";
$str = "[ta #12286152] c-d0-231-34 drop [#3414a43]"; 
$result = preg_replace('~\[[^][]*' . $id . '[^][]*]~', '', $str);
echo $result;