K. Kirkov K. Kirkov -4 years ago 132
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,
it is replaced okay, but when put
, all subject was removed?

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

I want to replace all in
that have MY id.

Answer Source

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 [^]]:


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;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download