开发者

Transforming user input into a list array in PHP

开发者 https://www.devze.com 2023-02-19 01:40 出处:网络
I have a textarea field.The output will be a HTML list.Each line will be a new list item.If a user type in a hypen (\'-\') then the list item will be nested

I have a textarea field. The output will be a HTML list. Each line will be a new list item. If a user type in a hypen ('-') then the list item will be nested

Sample
test1
te-st2
-test3
-test4
--test5
--test6
-test7
test8
-test9
test10

Output should be
Array (test1, 
       te-st2,
       array(test3, 
             test4,
             array(test5, test6),
             test7
       ),
      test8,
      array(test9),
      test10

I am not worry about the key values. I then run them开发者_StackOverflowe_item_list from http://api.drupal.org/api/drupal/includes--theme.inc/function/theme_item_list To create the list


try this (this has not been tested so it may need a little tweaking):

 $sample = "test1
te-st2
-test3
-test4
--test5
--test6
-test7
test8
-test9
test10"

$arr = explode("\n",$sample);
foreach($arr as $key=>$val){
    if($val[0] == '-'){
        unset($val[0]);
        if($val[1] == '-'){
            unset($val[0]);
            unset($arr[$key]);
            $arr[$key-1][] = $val;
        }
        else {
            $arr[$key] = array($val);
        }      
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消