2012-04-06 2 views
1

텍스트 내에서 단어와 구문을 추출해야합니다. 예를 들어, 텍스트는 다음과 같습니다PHP에서 preg_split()을 사용하여 단어 및 구문을 추출하는 방법은 무엇입니까?

안녕하세요, "일본과 중국", 미국인, 아시아 인, "유대인과 기독교인"반 카톨릭, preg_split()를 사용하여 여호와의 증인

, 그것은 반환해야 다음

  1. 안녕하세요
  2. 세계
  3. 일본과 중국
  4. 미국인
  5. 아시아 의
  6. 유대인과 기독교인
  7. 반 카톨릭
  8. Jehova의
  9. 증인
  10. 나는 일이의 정규식을 알 필요가

(또는 가능합니까?). 영숫자, 작은 따옴표 (') 및 대시 (-)는 단어의 일부로 간주되므로 ("여호와의"와 "세미 카톨릭"은 한 단어로 간주됩니다), 나머지 공백으로 구분 된 단어는 하나의 단어로 간주되지만 언급되지 않은 다른 기호는 무시됩니다.

+0

당신은 고려 대시 따옴표를 만들기 위해'\의 S +'를 사용할 수 있습니다. – hjpotter92

답변

1
을 :.와

$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); 

참고 작동합니다.

당신은 실제로 같은 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

감사합니다. 좋은 해결책 같아 보입니다. –

+0

하지만 어구의 내용은 변경되지 않고 그대로 유지되어야하며 변경 될 수도 있습니다. 예를 들어 "유대인, 무슬림 및 기독교인"이라는 구절이 있다면 "유대인 회교도와 기독교인"으로 변환 될 것입니다. – Pere

0

예를 들어 문자열이 일반적이면 큰 따옴표로 시작하십시오. 여기서는 heredoc syntax을 사용하여 문자열을 안전하게 만들었습니다. 또한 preg_replace이다 사용할 수 있지만, 이런 일에 대한 잔인한 것 같아

관련 문제