2012-11-10 38 views
4

我需要刪除搜索字符串的下一個單詞..我有陣列('aa','bb','é')搜索數組;PHP刪除搜索字符串旁邊的單詞

這是我的段落'你好,這是一個測試段aa 123測試bb 456'。

在這一段我需要刪除123和456

$pattern  = "/\bé\b/i"; 
$check_string  = preg_match($pattern,'Hello, this is a test paragraph aa 123 test é 456'); 

如何獲得下一個單詞?請幫忙。

回答

2

這裏是我的解決方案:

<?php 

//Initialization 
$search = array('aa','bb','é'); 
$string = "Hello, this is a test paragraph aa 123 test bb 456"; 

//This will form (aa|bb|é), for the regex pattern 
$search_string = "(".implode("|",$search).")"; 

//Replace "<any_search_word> <the_word_after_that>" with "<any_search_word>" 
$string = preg_replace("/$search_string\s+(\S+)/","$1", $string); 

var_dump($string); 

更換了 「SEARCH_WORD NEXT_WORD」 與 「SEARCH_WORD」,從而消除 「NEXT_WORD」。

+0

我想你的代碼,但它不會刪除123和456 – Kathiravan

+0

@Kathiravan:它確實對我來說。你使用的是什麼版本的PHP? –

+0

我不知道preg_replace函數preg_replace(「/ $ search_string \ s +(\ w +)/」,「$ 1」,$ string);這裏$ 1會做什麼。 – Kathiravan

0

您可以簡單地使用PHPS preg_replace()功能如下:

#!/usr/bin/php 
<?php 

// the payload to process 
$input = "Hello, this is a test paragraph aa 123 test bb 456 and so on."; 

// initialization 
$patterns = array(); 
$tokens = array('aa','bb','cc'); 

// setup matching patterns 
foreach ($tokens as $token) 
    $patterns[] = sprintf('/%s\s([^\s]+)/i', $token); 


// replacement stage 
$output = preg_replace ($patterns, '', $input); 

// debug output 
echo "input: ".$input."\n"; 
echo "output:".$output."\n"; 

?>