开发者

Creating menu from Text

I am very new to PHP programming and dont know the exact syntax of various labrary functions like , split, find ,etc. I am havi开发者_C百科ng following text with me in a string variable

$menu = '/home-page|HOME
/our-iphone-app|OUR iPhone APP
/join-us|JOIN ME
/contact-us|CONTACT US';

I want to populate to arrays with this text one array containing the portion before the pipe | and second array contains portions after pipe. How to do this using some split by char(|) method.

Finally arrays must contain

$arraypage = {'0'->'/home-page','1'->'/our-iphone-app'} // etc, and...
$arrayTitle = {'0'->'HOME','2'->'OUR iPhone App'} // etc


You need to break up the string by new lines and then by pipe characters.

$lines = explode("\n", $menu);
$arraypage = array();
$arrayTitle = array();

foreach($lines as $line) {
    list($arraypage[], $arrayTitle[]) = explode('|', $line);
}

var_dump of the resulting arrays gives:

array
  0 => string '/home-page' (length=10)
  1 => string '/our-iphone-app' (length=15)
  2 => string '/join-us' (length=8)
  3 => string '/contact-us' (length=11)

array
  0 => string 'HOME' (length=4)
  1 => string 'OUR iPhone APP' (length=14)
  2 => string 'JOIN ME' (length=7)
  3 => string 'CONTACT US' (length=10)


$array = explode("\n", $array);
$result1 = array();
$resutl2 = array();

foreach($array as $arr){
    $temp = explode('|', $arr);
    $result1[] = $temp[0];
    $result2[] = $temp[1];
 }


I'd suggest you make your string contain another separator like so:

$menu = '/home-page|HOME:/our-iphone-app|OUR iPhone APP:/join-us|JOIN ME:/contact-us|CONTACT US';

Then you can use the explode method to split up your string to an associative array.

$array = explode(":", $menu);
foreach($array as $key => $val) {
     $array[$key] = explode("|", $val);
}


I'd probably just define the data in an array to start with, rather than as a string. I'd also build it in the format

$menu_array = {
  {'url'=>'/home-page','text'=>'HOME'},
  {'url'=>'/our-iphone-app','text'=>'OUR iPhone APP'},
  {'url'=>'/join-us','text'=>'JOIN ME'},
  {'url'=>'/contact-us','text'=>'CONTACT US'},
};

Since that's almost certainly going to be more useful for whatever you do with it next.

If you do need to use a string for some reason though, I'd say a regular expression is the tidiest way to do this. The following:

preg_match_all('/^(?P<url>[^|]+)\\|(?P<text>\\V+)\\v*$/m',$menu,$menu_array,PREG_SET_ORDER)

would set $menu_array to the format I used above. In fairness, using a regular expression for this may be a little overkill, but I prefer the power of regexes, which are easier to tweak later when you want to add things than loops of explode()s.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜