Question

I'm looking to replace a substring with a new value of varying length. I've got a vague grasp on substr_replace, but it's leaving extra characters if the relacement string is shorter than the original.

The basic string I need to edit looks something like this

In Target(+-50%): <span style="color: red">33%</span>(1/3)<br>

I need to replace everything after the closing > of the span tag and before the opening < of the br tag. However, the number of characters will vary.

For Example: the string I want to remove is "33%(1/3)" which is 7 characters. I want to replace it with "9%(9/100)" which is 16 characters. I don't want to overwrite the br tag.

This seems like it should be simple, but I can't get my head around it. Should I be looking at preg_replace?

Was it helpful?

Solution

<?php
$subject = 'In Target(+-50%): <span style="color: red">33%</span>(1/3)<br>';
$pattern = '/<span\b[^>]*>(.*?)<\/span>(.*?)<br>/';
preg_match($pattern, $subject, $matches, PREG_OFFSET_CAPTURE, 3);
$subject = str_replace($matches[1][0], 'REPLACE WITH THIS TEXT', $subject);
$subject = str_replace($matches[2][0], 'REPLACE SECOND PART WITH THIS TEXT', $subject);

print_r($subject);
?>

OTHER TIPS

This should separate what you need:

preg_match('#(<span[^>]*>)(\d+\%)(</span>)(\(\d+/\d+\))#', $str, $matches);
var_dump($matches);

Then you can use str_replace with the matches.

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