2016-12-25 73 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; 
相关问题