如何在PHP中使用preg_split()提取单词和短语?

时间:2012-04-06 09:21:04

标签: php regex preg-split

我需要提取文本中的单词和短语。例如,文本是:

Hello World,“日本和中国”,美国人,亚洲人,“犹太人和基督徒”,以及半天主教徒,耶和华的见证人

使用preg_split(),它应该返回以下内容:

  1. 你好
  2. 世界
  3. 日本和中国
  4. 美国人
  5. 亚洲人
  6. 犹太人和基督徒
  7. 半天主教徒
  8. Jehova的
  9. 证人
  10. 我需要知道RegEx才能使用(或者可能吗?)。请注意规则,短语用引号括起来(“)。字母数字,单引号(')和破折号( - )被认为是单词的一部分(这就是为什么”耶和华“和”半天主教徒“被认为是一个单词),用空格分隔的休息被视为单个单词,而未提及的其他符号被忽略

2 个答案:

答案 0 :(得分:1)

你可以用str_getcsv这样简单地完成它:

// replace any comma or space by a singe space
$str = preg_replace('/(,+[ ]+)|([ ]+)/', ' ', $str);
// treat the input as CSV, the delimiters being spaces and enclusures double quotes
print_r(str_getcsv($str, ' ', '"'));

输出:

Array
(
    [0] => Hello
    [1] => World
    [2] => Japan and China
    [3] => Americans
    [4] => Asians
    [5] => Jews and Christians
    [6] => and
    [7] => semi-catholics
    [8] => Jehovah's
    [9] => witnesses
)

答案 1 :(得分:0)

如果您的示例字符串是典型的,则首先处理单引号和双引号。我在这里使用heredoc syntax来使字符串安全可用。

$string = <<<TEST
Hello World, "Japan and China", Americans, Asians, "Jews and Christians", and semi-catholics, Jehovah's witnesses
TEST;
$safe_string = addslashes($string);//make the string safe to work with
$pieces = explode(",",$safe_string);//break into pieces on comma
$words_and_phrases = array();//initiate new array

foreach($pieces as $piece)://begin working with the pieces
    $piece = trim($piece);//a little clean up
    if(strpos($piece,'"'))://this is a phrase
        $words_and_phrases[] = str_replace('"','',stripslashes($piece));
    else://else, these are words
        $words = explode(" ",stripslashes($piece));
        $words_and_phrases = array_merge($words_and_phrases, $words);
    endif;
endforeach;
print_r($words_and_phrases);

注意:您也可以使用preg_replace,但对于类似的内容来说似乎有些过分。