I want to find any dollar amount in a string and wrap it with span tags.
For instance I would like to edit this string:
Save $15 when you spend $150.
Into this:
Save <span>$15</span> when you spend <span>$150.</span>
This is what I've got so far:
$the_text = "Save $15 when you spend $150.";
if (preg_match('/(?<=\$)\d (\,\d )?\b/', $the_text, $regs)) {
foreach ($regs as $amount) {
$offer_text = str_replace("$","<span>$",$offer_text);
$offer_text = str_replace($amount,$amount."</span> ",$offer_text);
}
}
This works for me whenever there's just one dollar amount in the string, or if the string contains multiple dollar amounts with different integers. But in this particular case the code outputs the following:
Save <span>$15</span> when you spend <span>$15</span>0.
Any idea on how to improve the code in order to catch all cases?
CodePudding user response:
I'm no PHP-expert but when I fiddled around with it I just used:
\$\d (?:,\d )?\b
And replaced it with <span>$0</span>
. See an online demo
\$\d
- A literal dollar sign and 1 digits.(?:,\d )?
- Optional non-capture group to match a comma and 1 digits.\b
- A word-boundary.
<?php
$the_text = "Save $15 when you spend $150.";
echo preg_replace('/\$\d (?:,\d )?\b/', '<span>$0</span>', $the_text);
?>
Save <span>$15</span> when you spend <span>$150</span>.