duanju8431 2014-09-01 19:25
浏览 57
已采纳

如何在PHP中将<br>转换为(un)有序列表?

I have an array which is coming from db. Array has strings which is delimited by <br>. So I want to explode them and convert it to a

<ul>
    <li>...</li>
</ul> 

structure using a function (listIt($list)):

function listIt($list)
{
  $list = mb_convert_case($list, MB_CASE_TITLE, 'UTF-8');
  $text = explode('<br>', $list);
  $menu = '<ul>';

  foreach ($text as $li)
  {
    $menu .= '<li>' .   $li . '</li>';
  }

  return $menu . '</ul>';
}

My Array (rawMenu) is the following:

 array (size=5)
  0 => string 'Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee' (length=62)
  1 => string 'Soup<br>Potato<br>Chicken<br>Fish<br>Juice<br>Wine<br>Salad' (length=61)
  2 => string 'Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee' (length=62)
  3 => string 'Soup<br>Potato<br>Chicken<br>Fish<br>Juice<br>Wine<br>Salad' (length=61)
  4 => string 'Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee' (length=62)

The problem is string which I pass to listIt($rawMenu[4]) function returns:

<ul>
   <li>Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee</li>
</ul>
  • 写回答

1条回答 默认 最新

  • douhan0562 2014-09-01 19:32
    关注

    This happens because MB_CASE_TITLE converts the first letter to upper case (<Br>), then you have to split on Br:

    $st = 'Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee';
    $list = mb_convert_case($st, MB_CASE_TITLE, 'UTF-8');
    $text = explode('<Br>', $list);
    
    $menu = '<ul>';
    foreach ($text as $li){
      $menu .= '<li>' .   $li . '</li>';
    }
    $menu .= '</ul>';
    
    print_r($menu);
    

    Outputs:

    <ul><li>Banana</li><li>Cheese</li><li>Egg</li><li>Salad</li><li>Water</li><li>Juice</li><li>Coffee</li></ul>
    

    Working example in sandbox here.

    As noted in the comments by @LightnessRacesinOrbit good practice would be to swap explode and conversion:

    $st = 'Banana<br>Cheese<br>Egg<br>Salad<br>Water<br>Juice<br>Coffee';
    $text = explode('<br>', $st);
    
    $menu = '<ul>';
    foreach ($text as $li){
      $menu .= '<li>' .   $li . '</li>';
    }
    $menu .= '</ul>';
    $menu = mb_convert_case($menu, MB_CASE_TITLE, 'UTF-8');
    
    print_r($menu);
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化
  • ¥15 Mirare PLUS 进行密钥认证?(详解)
  • ¥15 物体双站RCS和其组成阵列后的双站RCS关系验证
  • ¥20 想用ollama做一个自己的AI数据库
  • ¥15 关于qualoth编辑及缝合服装领子的问题解决方案探寻
  • ¥15 请问怎么才能复现这样的图呀