我正在寻找PHP中的最佳方法,而不是使用JavaScript来从<a>
元素中删除所有其他文本或标记,但<spans>
除外。父<a>
元素未向目标提供类名或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>'
答案 0 :(得分:1)
$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;
}
答案 1 :(得分:0)
根据@ 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;
}
?>