如何使用 php 去除特定元素以外的文本

How to use php to strip text except specific elements

而不是 JavaScript,我正在寻找最好的方法,在 PHP 中,从 <a> 元素中去除所有其他文本或标记,除了 [=16] =].父 <a> 元素不提供目标的 class 名称或 ID。例如:

我有这个PHP:

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

生成这个 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>

我希望最终结果是:

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

我理解逻辑将类似于以下具有适当剥离语法的内容:

if this = '<span>icontext</span>somemoretexttohide1!'
else if this = '<span>icontext</span> some more text to hide1!'
should just = '<span>icontext</span>'
$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;
}

根据@ben-shoval 的指导,结果是这样的。效果很好!如果有人对性能改进或更清洁的方式有任何进一步的建议,请提出并投票。

<?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;
}
?>