Specific preg_replace issue - taking a parameter from the search pattern and plugging it into replacement pattern?

StackOverflow https://stackoverflow.com/questions/22996282

  •  01-07-2023
  •  | 
  •  

Question

Ok, how would I do something like this... if I have a replacement pattern called:

$replacement = '<div class="coupon"><input type="text" value="" /></div>';

and I'd like to search for all cases of either:

<input type="text" size="15" name="coupon" id="coupon" />

or

<input type="text" size="15" name="coupon" id="coupon" value="xyz" />

and if found, replace that with the $replacement variable, except that if found the match like in the 2nd case, how would I take out the xyz value from "value" parameter in that input field and plug it into the $replacement's value parameter so that in the end I get this as the $output value:

<div class="coupon"><input type="text" value="xyz" /></div>

(in case the original input field had xyz as the value, and if not then the value would be empty)

Is that even possible?

And I probably need to run two of these preg_replace statements to make this happen for both cases, so this one as the first one kinda works:

$output = preg_replace('<<input type="text" size="15" name="coupon" id="coupon" />>', $replacement, $output);

but how do I do it for the second one?

or is there a way to write it all as one statement that covers both conditions?

I'm just lost here.

Thanks!

Was it helpful?

Solution

You can do this a couple of different ways. If you're wanting to use the variable $replacement that you created, you can use preg_replace_callback to do that. But it would be far simpler to just use it in the expression like this:

// CREATE AN EXAMPLE STRING
$string = '<input type="text" size="15" name="coupon" id="coupon" value="xyz" />
<input type="text" size="15" name="coupon" id="coupon" />';

// DO THE REPLACEMENT
$string = preg_replace('~<input type="text" size="15" name="coupon" id="coupon"( value="([A-Z0-9]+)")? />~i', '<div class="coupon"><input type="text" value="$2" /></div>', $string);

This will output the following:

<div class="coupon"><input type="text" value="xyz" /></div>
<div class="coupon"><input type="text" value="" /></div>

Here is a demo of the REGEX

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top