I have a long string that contains a styled tag that I want to remove and replace with some other string.
However I’ve tried the str_replace function but it has failed. Any idea how I can do that? My code is here.
$primaryNav = '<li id="menu-item-1178" class="menu-item menu-item-type-post_type menu-item-object-page menu-item-1178 sf-ul">
<a href="http://mysite.com/join/" class="sf-with-ul">
<cufon class="cufon cufon-canvas" alt="Get " style="width: 30px; height: 15px; ">
<canvas width="45" height="16" style="width: 45px; height: 16px; top: -1px; left: -2px; "></canvas>
<cufontext>Get </cufontext>
</cufon>
<cufon class="cufon cufon-canvas" alt="in" style="width: 15px; height: 15px; ">
<canvas width="24" height="16" style="width: 24px; height: 16px; top: -1px; left: -2px; "></canvas>
<cufontext>in</cufontext>
</cufon>
<span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span></a>
<ul class="sub-menu" style="visibility: hidden; display: none; "> </ul>
</li>';
$primaryNav = str_replace('<span class="sf-sub-indicator"><cufon class="cufon cufon-canvas" alt="»" style="width: 6px; height: 15px; "><canvas width="20" height="16" style="width: 20px; height: 16px; top: -1px; left: -2px; "></canvas><cufontext>»</cufontext></cufon></span>', ' It works!', $primaryNav);
You need to account for the spaces between tags. This is one case where regular expressions might be a decent solution:
The
#is used to start/end the regex so you can ignore it. The\s*means match any number of spaces, as many times as you can. This will cover spaces, tabs, linebreaks, etc.Note that you can also, using regex, match a lot less if you don’t need as much detail:
Note that this last one will stop matching at the first
</span>, so if you have more than one, you’ll need to be careful – regular expressions do not support this kind of ‘balancing’.