Hi, I want to replace in a string all instances of width="xxx" by width="400" but only if xxx > 400. My first approach with no condition is using: preg_replace('/width="(\d+?)"/i', 'width="400"', $string); Is it possible to use a conditional pattern in that case? And how?
preg_replace('/width="(4[0-9]+[0-9]+)"/i', 'width="400"', $string); PHP: Replace every thing starting with 4XX should do it. Peace,
Is it possible to use a regular expression with a conditional pattern to replace any number greater than 400 in the second term of the preg_replace? I tried this: preg_replace('/width="(.*?)"/i', '/(?(\\1 > 400) width="400")/', $string); but it did not work. Any idea?
You're making it alot more complicated than it needs to be. Check out preg_replace_callback, you can specify a function to handle replacement with it.
Thanks a lot, Joebert ! Here is the final working code, if anyone is interested: function limitWidth($matches) { if ($matches[1] > 400) return 'width="400"'; return $matches[0]; } $string = preg_replace_callback('/width="(\d+?)"/i', 'limitWidth', string);