使用php将列表转换为数组.怎样


Convert list into an array using php. How?

我有一个名为listelements()的函数,它输出类似<li>text1</li><li>text2</li>的文本。

我有500多个元素。现在我想把它转换成一个数组。

有人能帮我吗?谢谢

注意:我使用的是php

更新:

我想要实现的是按字母顺序导航。到目前为止,我的函数按列表顺序显示链接。相反,我想把它放在一个数组中。然后我想用字符过滤它们。

$valid_characters = range( 'a' , 'z' );
$valid_numbers = array(1,2,3,4,5,6,7,8,9,0);

当用户点击"A"时,我想只显示以A开头的链接。希望这个解释能帮助你们更好地理解我的问题

<?php
$output = listelements();
$array = explode("<li>", $output);
//First element will be empty, so remove it
unset($array[0]);
// Now remove "</li>" at end of input
array_walk($array, create_function('&$val', '$val = str_replace("</li>", "", $val)'));
// $array should now contain your elements

explore对于html标记(将它们视为多个分隔符)不会很好地发挥作用。

如果CPU时间不是问题,请尝试使用preg_match,例如:

<?PHP
$input='<li>text1</li><li>text2</li><LI><p>text3</p></lI><Li>text fou4r</li>';
preg_match_all('(<(li|Li|LI|lI)>(.*)</(li|Li|LI|lI)>)siU', $input, $output);
print_r($output[2]);
?>


输出:

Array
    (
        [0] => text1
        [1] => text2
        [2] => <p>text3</p>
        [3] => text fou4r
    )
$strarr=explode("<li>",$string); //Breaks every <li>
$i=(-1); //Makes -1 as array starts at 0
$arr=array(); //this will be your array
foreach($strarr as $expl){ //Go through all li's
$ai=explode("</li>",$expl);//Get between the li. If there is something between </li> and <li>, it won't return it as you don't need it
if($i!=(-1))$arr[$i]=$ai[0]; //First isn't valid
$i=$i+1; //add i plus one to make it a real array
}

您可以使用simple_html_domhttps://simplehtmldom.sourceforge.io/manual.htm

require_once(./simple_html_dom.php);
$html = "<ul class=''><li class=''>Swagger transforms unfreshmen into legends of confidence</li><li class=''>Red Zone collection</li><li class=''>Enhances awesomeness</li><li class=''>Continue your confidence with Swagger Anti-perspirant & Deodorant and Body Spray</li><li class=''>Old Spice Red Zone Swagger Scent Men’s Bar Soap</li></ul>";
$result = li_to_array($html);
var_dump($result ); 
    
function li_to_array($str)
{
    if (is_string($str) && !empty($str)) {
        $html = str_get_html($str);
        $results= array();
        $response_results = $html->find('li');
        foreach ($response_results as $response_result){
            array_push($results, $response_result->plaintext);
        } 
        unset($html); //release memory
        return  $results;
    } else {
        return false;
    }
}

使用"preg_match"

以下是更多详细信息:http://www.php.net/manual/en/function.preg-match-all.php