-3

This question is NOT a duplicate and should not be marked as such!

I have done my research and have not found a solution. Standard replacements are not a solution here (How do I replace certain parts of my string? is not helpful). It is very annoying that every question asked on Stack Overflow is marked as duplicate and closed directly after less than 5 minutes. Obviously without even having read/understood the question.

Back to the problem:

Here's an example:

<?php
$string  = '<span class="X">001</span>';
$string .= '<span class="X">444</span>';
$string .= '<span class="X">242</span>';
$string .= '<span class="X">334</span>';
?>

Now I want to replace every occurrence from <span class="X"> to <span> (including the ! unknown ! number contained) with another string, for example <div title="yay">Icecream</div>.

So that the result could be:

<?php
echo $string;
// outputs:
// <div title="yay">Icecream</div>
// <div title="yay">Icecream</div>
// <div title="yay">Icecream</div>
// <div title="yay">Icecream</div>
?>

How can this be achieved?

prebiz
  • 11
  • 2
  • 1
    Why not use any regular expression for this? Also, are you sure that the given markup is invalid? You are opening a lot of spans without closing them – Nico Haase Apr 11 '21 at 13:59
  • 1
    What have you tried to find a solution for this problem? – Nico Haase Apr 11 '21 at 14:00
  • 1
    Also, as https://stackoverflow.com/questions/67044833/possibility-to-replace-strings-with-varying-contents-in-php has been closed already, why not share more details instead of simply reposting your problem? – Nico Haase Apr 11 '21 at 14:01
  • 2
    Tempted to close this with an arbitrary duplicate, just because of the preamble. It's not like this isn't asked five times a day. – mario Apr 11 '21 at 14:01
  • 1
    I understand you might be frustrated as I assume your previous questions might be removed. But honestly saying even with this question it is unclear what you are asking that is different from that question you pointed out. Can you be more clear of what is the purpose for what you try acheive? – Zankrut Parmar Apr 11 '21 at 14:06
  • "Five times a day" might be exaggerated, but please add some attempts of resolving a problem next time you ask a question – Nico Haase Apr 11 '21 at 14:35

1 Answers1

0

For anyone facing the same problem, here's a possible answer:

<?php
$string  = '<span class="X">001</span>';
$string .= '<span class="X">444</span>';
$string .= '<span class="X">242</span>';
$string .= '<span class="X">334</span>';

$replace = preg_replace('#<span class="X">.*</span>#m', '<div title="yay">Icecream</div>', $string);

echo $replace;

?>
prebiz
  • 11
  • 2