2012-01-17 60 views
0

是否可以使用php的preg_replace刪除除特定單詞外的任何字符串?替換除PHP中的特定單詞以外的所有內容

例如:

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

我想刪除一切,除了 「測試」 和 「PHP」 所以這將是:

$text will be 'test php' 

回答

1

你總是可以使用callback。在PHP 5.3:

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

或者:

$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 2012-01-17 18:40:44

+0

@AbuSara:正則表達式仍然必須遍歷整個文本。 – outis 2012-01-17 19:00:40

+0

@AbuSara,如果你的文字很大,那麼最好拉出你想要的單詞,而不是去掉你不想要的世界。 'preg_match_all'應該這樣做。 – Xeoncross 2012-01-17 19:25:42

相關問題