Search code examples
phpsubstr

Find nth word/element of string and replace it


I have long unordered list (<ul>) which i need to divide to three columns. I have something like this:

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

...and now i need to find nth element ($sep) of $ul and replace it.

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

EDIT:

My list look like this:

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

...and i want like this:

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

Solution

  • I ended up with this solution:

    $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>';