I have a function called listelements()
, which outputs text like <li>text1</li><li>text2</li>
.
I have more than 500 elements. Now I want to convert it into an array.
Can anyone help me? Thanks.
Note: I'm using php
The thing i want to achieve is alphabetical navigation. As of now my function displays links in list order. Instead of that i want to hold that in an array. Then i would like to filter them using characters.
$valid_characters = range( 'a' , 'z' );
$valid_numbers = array(1,2,3,4,5,6,7,8,9,0);
When the user click "A" i would like to display only links start with A. Hope this explanation helps you guys for better understanding my question
<?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
$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
}
Use "preg_match".
Here is more detail: http://www.php.net/manual/en/function.preg-match-all.php
explode won't do the trick nicely for html tags (considering them as multiple delimiters).
if CPU time is not a concern, try using preg_match, example below:
<?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]);
?>
output:
Array
(
[0] => text1
[1] => text2
[2] => <p>text3</p>
[3] => text fou4r
)