JonnyBorg JonnyBorg - 1 month ago 8
HTML Question

How to use php to strip text except specific elements

Instead of JavaScript, I am looking for the best way, in PHP, to strip out all other text or markup from within a

<a>
element, except
<spans>
. The parent
<a>
element does not provide a class name or id to target. For example:

I have this PHP:

<?php if ( has_nav_menu( 'social-menu' ) ) { ?>
<?php wp_nav_menu( array( 'theme_location' => 'social-menu', 'fallback_cb' => '' ) );?>
<?php}?>


Which generates this html:

<div>
<ul>
<li><a><span>icontext</span> some more text to hide1!</a></li>
<li><a><span>icontext</span> some more text to hide1!</a></li>
<li><a><span>icontext</span> some more text to hide1!</a></li>
</ul>
</div>


I'd like the end result to be:

<div>
<ul>
<li><a><span>icontext</span></a></li>
<li><a><span>icontext</span></a></li>
<li><a><span>icontext</span></a></li>
</ul>
</div>


I understand the logic would be something like the following with proper stripping syntax:

if this = '<span>icontext</span>somemoretexttohide1!'
else if this = '<span>icontext</span> some more text to hide1!'
should just = '<span>icontext</span>'

Answer
$text = "
  <div>
    <ul>
      <li><a><span>icontext</span> some more text to hide1!</a></li>
      <li><a><span>icontext</span> some more text to hide1!</a></li>
      <li><a><span>icontext</span> some more text to hide1!</a></li>
    </ul>
  </div>
  ";

$start = 0;
while ( strpos( $text, "</span>", $start ) <> FALSE ) {
  $start = strpos( $text, "</span>", $start );
  $length = strpos( $text, "</a>", $start ) - $start;
  $remove = substr( $text, $start, $length );
  $text = str_replace( $remove, "", $text );
  ++$start;
}