2012-04-06 26 views
1

我需要提取文本中的單詞和短語。例如,文本是:如何在PHP中使用preg_split()提取單詞和短語?

的Hello World,「日本與中國」,美國人,亞洲人,「猶太人和基督徒」,並半天主教徒,耶和華見證人

使用使preg_split(),它應該返回以下:

  1. 你好
  2. 世界
  3. 日本和中國
  4. 美國人
  5. 亞洲小號
  6. 猶太人和基督徒
  7. 半天主教徒
  8. Jehova的
  9. 證人

我需要知道的正則表達式這個工作(或這可能嗎?)。請注意,規則和短語用引號(「)括起來,字母數字,單引號(')和短劃線( - )被認爲是單詞的一部分(這就是爲什麼」耶和華「和」半天主教徒「被認爲是一個詞)用空格隔開的休息被視爲單個單詞,而其他未提及的符號被忽略

+0

你可以用'\ S +'作出考慮破折號和引號。 – hjpotter92 2012-04-06 09:25:15

回答

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 
) 
+0

謝謝..似乎是一個很好的解決方案 – 2012-04-09 05:46:33

+0

但可能短語的內容應該保持不變,這也改變了他們。例如,如果你有「猶太人,穆斯林和基督徒」這個短語,它會轉變爲「猶太人穆斯林和基督徒」。 – Pere 2015-10-31 12:05:42

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,但似乎矯枉過正這樣的事情

相關問題