2016-12-25 107 views
0
$str = 'This is a string with alphanumeric chars @ (test-exclude)'; 

要檢查字符串,我瞭解它的/^[a-zA-Z0-9]+$/,但我需要檢查字符串的每個單詞並從選擇中排除這些單詞。檢查單詞是否包含字母數字

在上面的字符串中,我需要它來排除@(test-exclude)

編輯:當然,我可以通過每個單詞和工藝,而是在尋找一種優雅的方式引起循環,我已經這樣做了:

array_unique(
    array_filter(
    explode(' ', 
     preg_replace("/^[a-zA-Z0-9]+$/", ' ', 
     implode(' ', 
      array_map('strtolower', 
      array_column(iterator_to_array($Cursor), 'description') 
     ) 
     ) 
    ) 
    ) 
) 
); 
+0

在空格上分隔並刪除那些包含非單詞字符的值。 – revo

+0

看來你只想在空白字符之間得到字母數字字符序列,所以,你可以使用['preg_match_all('〜(?<!\ S)[A-Z0-9] +(?!\ S)〜i' ,$ s,$ matches)'](https://regex101.com/r/rIxuVs/1)。 –

回答

2

explode的白色空間,然後做一個倒立preg_grep

print_r(preg_grep("/[^a-z0-9]/i", explode(' ', $str), PREG_GREP_INVERT)); 

輸出:

Array 
(
    [0] => This 
    [1] => is 
    [2] => a 
    [3] => string 
    [4] => with 
    [5] => alphanumeric 
    [6] => chars 
) 
0

您可以使用preg_match_all返回多個匹配。這些匹配可以包含一個字母數字字符,並以空格隔開或錨定在字符串的開頭或結尾:

<?php 

$str = 'This is a ^*&^*&^@$ string with alphanumeric chars @ (test-exclude)'; 

preg_match_all('/(?:^|\s)([a-z0-9]+)(?=$|\s)/i', $str, $matches); 

$cleanedstr = implode($matches[1], ' '); 

echo $cleanedstr; 
相關問題