4

我需要删除搜索字符串的下一个单词。我有像 array('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');

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

4

2 回答 2

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”。

于 2012-11-10T09:16:15.940 回答
0

您可以为此简单地使用 phpspreg_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";

?>
于 2012-11-10T09:17:02.580 回答