1

我有一些 html 菜单,最大宽度为 990px​​。现在我想从一个数组中打印这个菜单,并将这些菜单列表(<li>)放在一行中。删除填充空间或每个菜单列表,为了节省计算,如何将 foreach 中的总单词限制在 200 个字符内?我没有好主意,在我的代码中,将数组分组为字符串然后切割字符串长度,这不是一个好主意。

$a = array("item1","item2","item3" ... "item30");//'item' would be change to any other words.

foreach($a as $b){
   $c.=$b.'|';
}
function limitString($string, $limit = 200) {
    if(strlen($string) < $limit) {return $string;}
    $regex = "/(.{1,$limit})\b/";
    preg_match($regex, $string, $matches);
    return $matches[1];
}
$d = explode('|',limitString($c));
foreach($d as $e){
   echo '<li><a href="">'.$e.'</li>';
}

例如,如果第 200 个字符在 中item20,它应该被打破item19,在这个 foreach 中输出 19 个菜单列表。

4

3 回答 3

1

尝试以下操作:

$array = array("item1","item2","item3", "item4", "item5", "item6", "item7", "item8", "item9", "item10", "item11", "item12", "item13", "item14", "item15", "item16", "item17", "item18", "item19", "item20", "item21", "item22", "item23", "item24", "item25", "item26", "item27", "item28", "item29", "item30", "item31", "item32", "item33", "item34", "item35", "item36", "item37", "item38", "item39", "item40", "item41", "item42", "item43", "item44", "item45", "item46", "item47", "item48", "item49", "item50", "item51", "item52", "item53", "item54", "item55", "item56", "item57", "item58", "item59", "item60", "item61", "item62", "item63", "item64", "item65", "item66", "item67", "item68", "item69", "item70", "item71", "item72", "item73", "item74", "item75", "item76", "item77", "item78", "item79", "item80", "item81", "item82", "item83", "item84", "item85", "item86", "item87", "item88", "item89", "item90", "item91", "item92", "item93", "item94", "item95", "item96", "item97", "item98", "item99", "item100");
$max = 200;


$length = 0;
$menu_items = array();
foreach($array as $value){
    $length += strlen($value);
    if($length <= $max){
        $menu_items[] = $value;
    }else{
        break;
    }
}

// Outputing the menu:
echo '<ul><li>'. implode('</li><li>', $menu_items) .'</li></ul>';

在线演示

于 2013-04-26T14:54:29.810 回答
1

您可以substr()像其他评论所说的那样使用。要保留单词拆分,请查看此线程

无论如何,有一个更好的方法来处理字符串物理长度,但它涉及到 JavaScript。

您所要做的就是创建包含要测量的字符串的不可见 div,然后获取它的宽度和高度。为什么要这么做?当然,由于每个字母的宽度不同,不同操作系统上的不同浏览器也会以不同的方式显示字体。

于 2013-04-26T14:42:54.620 回答
0

您可以在这部分检查它:

foreach($a as $b){
if(strlen($c)<200)  $c.=$b.'|'; else return;
}
于 2013-04-26T14:45:06.880 回答