2014-01-29 31 views
1

在PHP我有一個這樣的數組:如何從數組中找到「http」字符串?

array 
    0 => string 'open' (length=4) 
    1 => string 'http://www.google.com' (length=21) 
    2 => string 'blank' (length=5) 

,但它也可能是這樣的:

array 
    0 => string 'blank' (length=5) 
    1 => string 'open' (length=4) 
    2 => string 'http://www.google.com' (length=21) 

現在很容易找到「空白」與in_array("blank", $array),但我怎麼可以看到,如果一個字符串以「http」開頭?

我試着

array_search('http', $array); // not working 
array_search('http://www.google.com', $array); // is working 

現在一切後`HTTP?可能會有所不同(如何寫不同,varie?可能不同,就是我的意思!)

現在我需要一個正則表達式嗎?或者我該如何檢查http是否存在於數組字符串中?

感謝建議

+0

也許這http://stackoverflow.com/questions/2354024/is-it-possible-to-use -regex-to-search-inside-an-array-using-php –

+0

帶有strpos的foreach循環怎麼樣? –

+0

那你[去](https://eval.in/96086),'preg_grep()'來救援! – HamZa

回答

2

「歡迎來到PHP,這裏有一個功能。」

嘗試preg_grep

preg_grep("/^http\b/i",$array); 

Regex的解釋:

/^http\b/i 
^\/^ `- Case insensitive match 
| \/ `--- Boundary character 
| `------ Literal match of http 
`--------- Start of string 
2

嘗試使用preg_grep函數返回該模式匹配的條目的陣列。

$array = array("open", "http://www.google.com", "blank"); 

$search = preg_grep('/http/', $array); 

print_r($search); 
2

解決方案,而不正則表達式:

$input = array('open', 'http://www.google.com', 'blank'); 
$output = array_filter($input, function($item){ 
    return strpos($item, 'http') === 0; 
}); 

輸出:

array (size=1) 
    1 => string 'http://www.google.com' (length=21) 
0

您可以使用preg_grep

$match = preg_grep("/http/",$array); 
if(!empty($match)) echo "http exist in the array of string."; 

,或者您可以使用foreachpreg_match

foreach($array as $check) { 
    if (preg_match("/http/", $check)) 
    echo "http exist in the array of string."; 
} 
+0

循環中的'preg_match()'非常慢,在這種情況下最好使用'strpos()' – HamZa

相關問題