PHP删除搜索字符串旁边的单词

时间:2012-11-10 09:02:08

标签: php

我需要删除搜索字符串的下一个单词..我有像数组一样的搜索数组('aa','bb','é');

这是我的段落'你好,这是一个测试段落aa 123 test bb 456'。

在本段中,我需要删除123和456.

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

如何获得下一个字?请帮忙。

2 个答案:

答案 0 :(得分: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”。

答案 1 :(得分: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";

?>