我需要在文本中提取单词和短语。例如,案文如下:
你好世界,“日本和中国”,美国人,亚洲人,“犹太人和基督教徒”,半天主教徒,耶和华见证人
使用preg_split(),它应该返回以下内容:
我需要知道RegEx才能让它工作(或者它有可能吗?)注意规则,短语被用引号(")括起来。字母数字,单引号(')和破折号(-)被认为是单词的一部分(这就是为什么“约娃”和“半天主教徒”被认为是一个单词的原因),其余用空格分隔的被认为是单字,而其他没有提到的符号则被忽略。
发布于 2012-04-06 12:54:11
实际上,您可以非常简单地使用这样的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
)发布于 2012-04-06 12:14:41
如果您的示例字符串是典型的,从处理单引号和双引号开始。我在这里使用了黑尔多语法来保证字符串的安全使用。
$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,但是对于类似的事情来说,这似乎太过了。
https://stackoverflow.com/questions/10041508
复制相似问题