php - 如何在 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'>→</span>";
}
}
$btn = rtrim($btn, '<span>→</span>');
print $btn . "</div>";
我试过了,rtrim
但这改变了整个 html 页面。还有任何其他解决方案可以删除 php 中的最后一个 html 元素foreach
。
解决方案
肯定有很多重复的,但我找不到。所以,你有两个,不,三个解决方案:
使用计数器并按
→
条件添加$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'>→</span>"; } $i++; } } print $btn . "</div>";
将项目添加到数组并
implode
使用→
$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'>→</span>", $btns); print $btn . "</div>";
substr
长度为 last 的最终字符串span
。mb_
如果您的数据是多字节编码的,您可能需要在此处使用-functions。$btn = substr($btn, 0, -1 * strlen("<span style='font-size:50px'>→</span>"));
推荐阅读
- django - 每个请求中的新 sessionid
- python - 从二进制掩码裁剪图像
- python-3.7 - 如何在 sanic 应用程序中为 tortoise-orm 初始化 db?
- jquery - 使用jQuery查找某些文本,如果存在,则将元素附加到附近的某个元素
- java - 在 Java 中解析来自 C++ 的 protobuf 消息的序列化字符串失败
- arrays - 在 Tradingview 下使用数组时在输入“[”处出现语法错误
- python - UnicodeEncodeError:字符映射到
用于写入存档 python - angular - 在 NgModule 中访问 location.host
- python - 将字符串转换为原始浮点数
- amazon-web-services - 使用 AWS Api Gateway 进行 Api 组合