首页 > 解决方案 > 如何在 PHP 中删除最后一个 html 实体

问题描述

我有以下代码,其中在 foreach 循环中添加了带有 html 实体的箭头。此 html 实体位于 span 标签中。我想删除最后一个箭头。

$btn = '<div style="margin: 5px;">';
if (count($rslt) > 0) {
    foreach ($rsltas as $key => $val) { //added as here
        $btn .= "<a class='btn btn-md'  href='index.php?target=$trgtName#" . trim(substr($val, 0, strpos($val, '-'))) . "'>" . $val . "</a><span style='font-size:50px'>&rarr;</span>";
    }
}
$btn = rtrim($btn, '<span>&rarr;</span>');
print $btn . "</div>";

我试过了,rtrim但这改变了整个 html 页面。还有任何其他解决方案可以删除 php 中的最后一个 html 元素foreach

标签: phphtml

解决方案


肯定有很多重复的,但我找不到。所以,你有两个,不,三个解决方案:

  • 使用计数器并按&rarr;条件添加

    $btn = '<div style="margin: 5px;">';
    if (count($rslt) > 0) {
        $i = 1;
        foreach ($rslt as $key => $val) {
            $btn .= "<a class='btn btn-md'  href='index.php?target=$trgtName#" . trim(substr($val, 0, strpos($val, '-'))) . "'>" . $val . "</a>";
            if ($i < count($rslt)) {
                $btns .= "<span style='font-size:50px'>&rarr;</span>"; 
            } 
            $i++;
        }
    }
    print $btn . "</div>";
    
  • 将项目添加到数组并implode使用&rarr;

    $btn = '<div style="margin: 5px;">';
    $btns = [];
    if (count($rslt) > 0) {
        foreach ($rslt as $key => $val) {
            $btns[] = "<a class='btn btn-md'  href='index.php?target=$trgtName#" . trim(substr($val, 0, strpos($val, '-'))) . "'>" . $val . "</a>";
        }
    }
    $btn .= implode("<span style='font-size:50px'>&rarr;</span>", $btns);
    print $btn . "</div>";
    
  • substr长度为 last 的最终字符串spanmb_如果您的数据是多字节编码的,您可能需要在此处使用-functions。

    $btn = substr($btn, 0, -1 * strlen("<span style='font-size:50px'>&rarr;</span>"));
    

推荐阅读