使用preg_match_all从字符串中提取单词

Gab*_*iel 2 php regex string keyword

我对正则表达式不好,但我想用它来从字符串中提取单词.

我需要的单词应该至少有4个字符,提供的字符串可以是utf8.

示例字符串:

Sus azahares presentangruesospétalosblancosteñidosderosaovioláceoenla parte externa,con numerosos estambres(20-40).

期望的输出:

Array(
    [0] => azahares
    [1] => presentan
    [2] => gruesos
    [3] => pétalos
    [4] => blancos
    [5] => teñidos
    [6] => rosa
    [7] => violáceo
    [8] => parte
    [9] => externa
    [10] => numerosos
    [11] => estambres
)
Run Code Online (Sandbox Code Playgroud)

Wal*_*oss 7

如果要查找的单词是UTF-8(至少4个字符长,根据规格),这适用于ISO-8859-15的字母字符(适用于西班牙语,适用于英语,德语,法语,等等.):

$n_words = preg_match_all('/([a-zA-Z]|\xC3[\x80-\x96\x98-\xB6\xB8-\xBF]|\xC5[\x92\x93\xA0\xA1\xB8\xBD\xBE]){4,}/', $str, $match_arr);
$word_arr = $match_arr[0];
Run Code Online (Sandbox Code Playgroud)


flo*_*ree 6

您可以使用下面的正则表达式来表示简单字符串.它将匹配任何非空格字符,最小长度= 4.

preg_match_all('/(\S{4,})/i', $str, $m);
Run Code Online (Sandbox Code Playgroud)

现在$m[1]包含您想要的数组.

更新:

正如戈登所说,这种模式也将与'(20-40)'相匹配.使用此正则表达式可以删除不需要的数字:

preg_match_all('/(\pL{4,})/iu', $str, $m);
Run Code Online (Sandbox Code Playgroud)

但我认为只有在使用UTF-8支持编译PCRE时它才有效.请参阅PHP PCRE(正则表达式)不支持UTF-8?.它可以在我的电脑上运行.