preg replace - PHP preg_match & preg_replace outputing wrong -


<?php $string = "[img image:left]1.jpg[/img]example text 1[img image:left]2.jpg[/img] example text 2"; preg_match("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $string, $match); $result = preg_replace("/\[img\s*[^>]+\s*\](.*?)\[\/\s*img\]/i", $match['1'], $string); echo $result; ?> 

when using code should output 1.jpg, example text 1, 2.jpg, example text 2.

but shows 2.jpg, example text 2.

i dont know i'm doing wrong.

there 2 fundamental issues:

  • you don't need use preg_match() , preg_replace(), can use preg_replace() , reference capture groups in substitution
  • it looks copy pasted code html regex, , have [^>]+ inside of [img], says 1+ non-> characters..it should [^\]]+, 1+ non-] characters

final solution:

$string = "[img image:left]1.jpg[/img]example text 1[img image:left]2.jpg[/img] example text 2"; $string = preg_replace("/\[img\s*[^\]]+\s*\](.*?)\[\/\s*img\]/i", ' \1 ', $string); 

demo: regex , php


Comments

Popular posts from this blog

commonjs - How to write a typescript definition file for a node module that exports a function? -

openid - Okta: Failed to get authorization code through API call -

thorough guide for profiling racket code -