2012-01-04 74 views
0

我在這裏得到了一個測試模式,但它不允許空格。preg_match不能與我的數組一起工作

$myarray[]='s s'; 
if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$myarray)>0) echo 'yes'; 

這確實不算什麼,但

$test='s s'; 
if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$test)>0) echo 'yes'; 

這工作得很好...... 我不明白爲什麼它不與我的數組工作?

+1

如果你看看[docs](http://php.net/manual/en/function.preg-match.php)你會看到該函數只接受一個字符串作爲主題,所以它並不奇怪,它不起作用:P – PeeHaa 2012-01-04 02:42:25

+0

preg-match不適用於數組 – 2012-01-04 02:45:54

回答

1

的preg_match不接受的陣列作爲輸入,只是一個單一的字符串。你需要做這樣的事情......

$matched = no; 
foreach($myarray as $x) { 
    if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$x)>0) $matched = true; 
} 
if($matched) echo 'yes'; 

要做到這一點在一個步:

function preg_match_any($regex,$array) { 
    foreach($array as $x) { 
     if (preg_match($regex,$x)>0) return true; 
    } 
    return false; 
} 

//Then to call it just something like: 
if (preg_match_any('/[^\d\w\(\)\[\]\.\-]+/',$myarray)) echo 'yes'; 
+0

哦,謝謝,明白了,我想我會堅持這一個,如果它不能在一個電話中完成。謝謝! :) – Anonymous 2012-01-04 02:48:06

+0

您可以輕鬆地創建一個簡單的功能,爲您做到這一點 - 我會更新我的答案... – SpoonNZ 2012-01-04 02:49:29

+0

噢,謝謝指出,我最終只是自己做了這個功能,並不認爲你會編輯你的文章:P這裏是我得到的: function u($ in){foreach($ in as $ x => $ a){preg_match('/ [^ \ d \ w \(\)\ [\] \。\ - ] + /',$ a)> 0)return(true);}}; if(u($ input))echo'yes'; – Anonymous 2012-01-04 03:14:53

2

您不能在數組上執行類似的操作。正如您在the documentation on preg_match()中看到的那樣,它將字符串作爲第二個參數,而不是數組。

int preg_match (string $pattern , string $subject 
     [, array &$matches [, int $flags = 0 [, int $offset = 0 ]]]) 

相反,你必須告訴它你想在它的操作元素。

如果你想這樣做只是一個數組的一個元素,只需使用它的索引。例如。第一個元素將是$myarray[0],所以下面應該工作:

if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$myarray[0])>0) echo 'yes'; 
如果您在另一方面

希望它做的每一個元素的數組中,你可以

  • 創建foreach循環

    foreach ($myarray as $element) { 
        if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$element)>0) echo 'yes'; 
    } 
    
  • 使用array_map()和CA llback功能

    function match_callback($element) { 
        if (preg_match('/[^\d\w\(\)\[\]\.\-]+/',$element)>0) echo 'yes'; 
    } 
    array_map('match_callback',$myarray); 
    
+0

謝謝,好吧,我只想得到一個單一的是,它如果任何數組元素都與模式匹配。 – Anonymous 2012-01-04 02:43:53

+0

@ user1125062如果是這樣,只需使用'foreach'循環。如果發現匹配,記得調用'break',否則循環會在匹配後經過數組的其餘部分,並可能多次寫入'yes'。 – kba 2012-01-04 02:47:24

0

不能使用數組作爲你的主題爲preg_match只接受一個字符串。你可以使用匿名函數(php 5.3+):

$ret = array_map(function($element) {  
    return preg_replace('/[^\d\w\(\)\[\]\.\-]+/', '', $element) > 0; 
}, $myarray); 
相關問題