找到字符串的第n个单词/元素并替换它

时间:2017-08-29 11:45:50

标签: php substr

我有很长的无序列表(<ul>),我需要将其分为三列。我有这样的事情:

$num = substr_count($ul, '<li>')/3;
$sep = round($num, 0);

...现在我需要找到$ ul的第n个元素($ sep)并替换它。

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

编辑:

我的列表如下所示:

<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>

......我想这样:

<ul>
<li>1</li>
<li>2</li>
</ul>
<ul>
<li>3</li>
<li>4</li>
</ul>
<ul>
<li>5</li>
<li>6</li>
</ul>

3 个答案:

答案 0 :(得分:2)

我总是喜欢使用本机函数来解析和操作HTML,在本例中为PHP's DOM classes

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/main_content"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/fragment_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_above="@id/bottom_navigation" />

    <android.support.design.widget.BottomNavigationView
        android:id="@+id/bottom_navigation"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:background="@color/navigationItemBackground"
        app:itemIconTint="@color/navigationItemIcon"
        app:itemTextColor="@color/navigationItemtext"
        app:menu="@menu/bottom_navigation_items"
        android:layout_alignParentStart="true" />

</RelativeLayout>

答案 1 :(得分:1)

这将获得一个无序的HTML列表,将其划分为三个UL,并将其吐回:

<?php
$ul = "<ul>
<li>1</li>
<li>2</li>
<li>3</li>
<li>4</li>
<li>5</li>
<li>6</li>
</ul>";
function divideUl($ul) {
    $ulArray = explode("\n", $ul);
    array_pop($ulArray);
    array_shift($ulArray);
    $num = substr_count($ul, '<li>')/3;
    $sep = round($num);
    $string = "<ul>";
    foreach ($ulArray as $i => $li) {
        if ($i % $sep === 0 && $i !== 0) $string .= "</ul>";
        if ($i % $sep === 0 && $i !== 0) $string .= "<ul>";
        $string .= $li;
    }
    $string .= "</ul>";
    return $string;
}
echo divideUl($ul);

Demo

答案 2 :(得分:0)

我最终得到了这个解决方案:

$ul = '<ul><li>1</li><li>2</li><li>3</li><li>4</li><li>5</li><li>6</li></ul>';

$doc = new DOMDocument();
$doc->loadHTML('<?xml encoding="UTF-8">' . $ul);
$liList = $doc->getElementsByTagName('li');
$liValues = array();
foreach ($liList as $li) {
    $liValues[] = $li->c14n();
}

$num = count($liValues) / 3;
$size = round($num+1);

$i = 0;
$list = '';

foreach ($liValues as $listItem) {

    if ($i !== 0 && $i % $size === 0) {
        $list.= '</ul><ul>';
    }

    $list.= $listItem;

    $i++;
}

echo '<ul>'.html_entity_decode(str_replace(array('</br>', '</img>'), '', $list)).'</ul>';