首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何在PHP中使用preg_split()提取单词和短语?

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

Stack Overflow用户
提问于 2012-04-06 09:21:03
回答 2查看 1.4K关注 0票数 1

我需要在文本中提取单词和短语。例如,案文如下:

你好世界,“日本和中国”,美国人,亚洲人,“犹太人和基督教徒”,半天主教徒,耶和华见证人

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

  1. 你好
  2. 世界
  3. 日本与中国
  4. 美籍
  5. 亚洲人
  6. 犹太人和基督教徒
  7. 半天主教徒
  8. 约瓦氏
  9. 证人

我需要知道RegEx才能让它工作(或者它有可能吗?)注意规则,短语被用引号(")括起来。字母数字,单引号(')和破折号(-)被认为是单词的一部分(这就是为什么“约娃”和“半天主教徒”被认为是一个单词的原因),其余用空格分隔的被认为是单字,而其他没有提到的符号则被忽略。

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2012-04-06 12:54:11

实际上,您可以非常简单地使用这样的str_getcsv:

代码语言:javascript
复制
// 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, ' ', '"'));

产出:

代码语言:javascript
复制
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
EN

Stack Overflow用户

发布于 2012-04-06 12:14:41

如果您的示例字符串是典型的,从处理单引号和双引号开始。我在这里使用了黑尔多语法来保证字符串的安全使用。

代码语言:javascript
复制
$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,但是对于类似的事情来说,这似乎太过了。

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/10041508

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档