如何在数组中的每组 li 之前找到 li 并注入 ul

我有一个 html 标签的索引数组,每个索引都包含 html 开始和结束标签及其值。我想修改其中一些,例如我希望 li 标签用 ul 包裹在它们周围。但具有相同的数组顺序。


Array

(

[0] => <li>some text</li>

[1] => <pre>text area data</pre>

[2] => <li>some value</li>

)

这就是我想要的样子


 Array

(

[0] => <ul>

[1] => <li>some text</li>

[2] => </ul>

[3] => <pre>text area data</pre>

[4] => <ul>

[5] => <li>some value</li>

[6] => </ul>

)


    $arr2 = [];

    $a=0;


    foreach($arr1 as $k => $v)

    {

        if($a == 0)

        $arr2[] = '<ul>';

        $a=1;

        

       if(strpos($v, '<li>') !== false){

        $arr2[] = $v;

    }


繁花如伊
浏览 95回答 1
1回答

九州编程

此代码跟踪您当前是否在列表中,然后针对每个项目检查它是否以开头<li>以及状态。如果它<li>不在列表中,则添加<ul>第一个并设置状态,如果不是,<li>则在列表中添加</ul>。为了确保它关闭任何列表,在循环之后如果它在列表中,那么它会关闭标签......$arr2 = [];$inList = false;foreach($arr1 as $index => $value){&nbsp; &nbsp; if ( substr(trim($value), 0, 4) == "<li>" ) {&nbsp; &nbsp; &nbsp; &nbsp; if ( ! $inList )&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arr2[] = '<ul>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $inList = true;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; else&nbsp; &nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; if ( $inList )&nbsp; {&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $arr2[] = '</ul>';&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; $inList = false;&nbsp; &nbsp; &nbsp; &nbsp; }&nbsp; &nbsp; }&nbsp; &nbsp; $arr2[] = $value;}if ( $inList )&nbsp; {&nbsp; &nbsp; $arr2[] = '</ul>';&nbsp; &nbsp; $inList = false;}
打开App,查看更多内容
随时随地看视频慕课网APP