我有以下代码,其中在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>";
Run Code Online (Sandbox Code Playgroud)
我尝试过,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>";
Run Code Online (Sandbox Code Playgroud)将项目添加到数组并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>";
Run Code Online (Sandbox Code Playgroud)substr最后一个字符串,长度为last span。mb_如果您的数据是多字节编码的,那么在这里您可能需要使用-functions。
$btn = substr($btn, 0, -1 * strlen("<span style='font-size:50px'>→</span>"));
Run Code Online (Sandbox Code Playgroud)| 归档时间: |
|
| 查看次数: |
49 次 |
| 最近记录: |