Question

I have a big string that is a combination of many blocks (chunks) of data:

{Hello user, good morning \br}{Welcome user, this is just a static text, continue to next page}{Hope you are doing well \br enjoy your stay here.}

What i would like to do is, to remove the chunks from it, that contain a specific character set: \br.

So the above string should be:

{Welcome user, this is just a static text, continue to next page}

I have tried preg_replace, without luck:

$a = "{Hello user, good morning \br}{Welcome user, this is just a static text \br continue to next page}{Hope you are doing well \br enjoy your stay here.}";
$b = preg_replace('/\s+\br\s+/', "", $a);
print $b;
Was it helpful?

Solution

Try

$b = preg_replace('/{[^{]*\\br.*?}/', "", $a);

Breaking that into chunks:

  • { searches for a { character
  • [^{]* means "match any character that isn't a { any number of times (after all, if we find another { it means we're starting a new block. You could also use })
  • ? makes the previous match non-greedy, meaning we'll get the smallest group possible
  • \\br will match \br
  • .*? is a non-greedy match that will match anything that comes before...
  • } the closing brace
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top