GFL
GFL

Reputation: 1446

Preform multiple preg_replace inside matched text

If there is a comma and a space inside a pair of square brackets, I'm trying to replace it with a closing square bracket and an opening square bracket.

Basically, I have a block of text that looks like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi laoreet 
lobortis blandit. Proin in nulla mauris.[3, 8, 19, 45] Aenean dictum 
sollicitudin nibh, non semper mauris semper id.[52, 58] Donec at varius eros. 
Sed in risus nec tellus vehicula semper. In id elit vel nunc ornare faucibus. 
Integer feugiat erat mauris, in tempus leo imperdiet ac.[23]

That I'm trying to make look like this:

Lorem ipsum dolor sit amet, consectetur adipiscing elit. Morbi laoreet 
lobortis blandit. Proin in nulla mauris.[3][8][19][45] Aenean dictum 
sollicitudin nibh, non semper mauris semper id.[52][58] Donec at varius eros. 
Sed in risus nec tellus vehicula semper. In id elit vel nunc ornare faucibus. 
Integer feugiat erat mauris, in tempus leo imperdiet ac.[23]

I wrote a preg_replace function but it only performs the replacement if it exists one time inside the bracket set:

$output = preg_replace("/(\[\d*), (\d*\])/", "$1][$2", $input);

How can I modify my regex so it will perform multiple replacements inside the matched text?

Upvotes: 0

Views: 27

Answers (1)

revo
revo

Reputation: 48761

A quick way would be:

, (?=[^][]*\])

Live demo

Breakdown:

  • ,[ ] Match a comma following a space character
  • (?= Start of a positive lookahead
    • [^][]*\] Assert whether it follows a closing bracket without matching a bracket
  • ) End of lookahead

PHP code:

echo preg_replace('/, (?=[^][]*\])/', '][', $str);

But if it's likely to have a closing bracket somewhere in text without being opened, this is more bulletproof:

(?:\[(?=[^][]*\])|\G(?!\A))[^],]*\K, 

Live demo

Upvotes: 2

Related Questions