Search code examples
phphtmltrimstrip

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>'

Solution

  • Based on the direction from @ben-shoval, one result ended up being this. Works great! If anyone has any further suggestions for performance improvement or a cleaner way, have at it and vote up.

    <?php if ( has_nav_menu( 'social-menu' ) ) {
    
        // get the actual output of the html, but don't print it just yet.
        $menu = wp_nav_menu( array( 'theme_location' => 'social-menu', 'fallback_cb' => '', 'echo' => false ) );
    
        // start removing all text except what's inside the spans.
        $start = 0;
            while ( strpos( $menu, "</span>", $start ) <> FALSE ) {
            $start = strpos( $menu, "</span>", $start )+7;
            $length = strpos( $menu, "</a>", $start ) - $start;
            $remove = substr( $menu, $start, $length );
            $menu = str_replace( $remove, "", $menu );
            ++$start;
        }
    
        // now that it's modified let this HTML print to screen.
        echo $menu;
    }
    ?>