2011-06-29 25 views
1

圖案的子陣列考慮這個數組在PHP中:獲取與PHP

$list = array('apple','orange','alpha','bib','son','green','odd','soap'); 

我怎樣才能得到元素的子陣列開始字母「A」或「S」?

回答

7

http://php.net/manual/en/function.preg-grep.php

$items = preg_grep('~^[as]~', $list); 
+0

$ A = preg_grep( '#^ A | S#',array_map( '用strtolower',$列表));以防萬一你有混合的情況(在你的測試中使蘋果蘋果)。 +1發佈適當的PHP數組我們可以複製和使用。周到。 – Cups

+0

啊,好吧,好吧,那麼這是更好的$ a = preg_grep('#^ a | s#i',$ list); <-use i正則表達式 – Cups

1
$sublist = array(); 
for ($i = 0; $i < count($list); $i++) { 
    if ($list[$i][0] == 'a' or $list[$i][0] == 's') { 
     $sublist[] = $list[$i]; 
    } 
} 
+0

$ list [$ i] [0] < - 你可以在PHP中做到這一點嗎? = O從來沒有想過那個...... =]好的! =] – benqus

+0

@benqus:是的,PHP允許你使用數組偏移量給出一個字符串偏移量。就像任何涉及字符串的PHP操作一樣,如果在多字節字符集中有一個字符串,它也不會很好。 – Hammerite

0
for ($i =0; $i < count($list); $i++) { 
    if (substr($list[i], 1) == "a" || substr($list[i], 1) == "s") { 
     //put it in an other array 
    } 
} 
0
<?php 

$名單=陣列( '蘋果', '橙', '阿爾法' , '圍脖', '兒子', '綠', '奇', '肥皂');

$ tmp_arr = array(); foreach($ list as $ t) if(substr($ t,0,1)=='a'|| substr($ t,0,1)==''') { $ tmp_arr [] = $ t; } }

print_r($ tmp_arr);

>

//輸出:?陣列([0] =>蘋果[1] =>的α[2] =>子[3] =>皁)

0

這是一種方式這樣做:

$list = array('apple','orange','alpha','bib','son','green','odd','soap'); 


$a = array(); 
$s = array(); 
for ($i = 0; $i < count($list); $i++) 
{ 
    if (substr($list[$i], 0, 1) == "s") 
    { 
     $s[$i] = $list[$i]; 
    } 
    else if (substr($list[$i], 0, 1) == "a") 
    { 
     $a[$i] = $list[$i]; 
    } 
}