2012-01-17 3 views
0

PHP의 preg_replace를 사용하여 특정 단어를 제외한 문자열의 내용을 제거 할 수 있습니까? 예를 들어PHP의 특정 단어를 제외한 모든 것을 대체하십시오.

:

$text = 'Hello, this is a    test string from php.'; 

내가 그것을 할 수 있도록 "테스트"와 "PHP"를 제외한 모든를 제거하려면 :

$text will be 'test php' 

답변

1

당신은 항상 callback를 사용할 수 있습니다.

$keep = array('test'=>1, 'php'=>1); 

$text = trim(
    preg_replace(
     '/[^A-Za-z]+/', ' ', 
     preg_replace_callback(
      '/[A-Za-z]+/', 
      function ($matched) use (&keep) { 
       if (isset($keep[$matched[0]])) { 
        return $matched[0]; 
       } 
       return ''; 
      }, $text 
      ) )   ); 

또는 : PHP 5.3에서 제공된 코드에 대한

$text = 
    array_intersect(
     preg_split('/[^A-Za-z]+/', $text), 
     array('test', 'php') 
    ); 
0
$text = 'Hello, this is a    test string from php.'; 
$words = preg_split('~\W~', $text, -1, PREG_SPLIT_NO_EMPTY); 

$allowed_words = array('test'=>1, 'php'=>1); 
$output = array(); 
foreach($words as $word) 
{ 
    if(isset($allowed_words[$word])) 
    { 
     $output[] = $word; 
    } 
} 

print implode(' ', $output); 
+0

감사합니다, 나는 함수 preg_replace이다를 사용하고 싶습니다. 내 텍스트가 거대하고 모든 단어를 반복하지 않으려 고합니다. – PyQL

+0

@AbuSara : 정규 표현식은 전체 텍스트를 반복해야합니다. – outis

+0

@AbuSara, 만약 당신이 텍스트가 거대하다면, 당신이 원하지 않는 세계를 제거하는 것보다 원하는 단어를 끌어내는 것이 낫습니다. 'preg_match_all'이 그렇게해야합니다. – Xeoncross

관련 문제