如何在一口中匹配和替换PHP?
类似这样,但我不想重复两次:如何在一口中匹配和替换PHP?,php,string,Php,String,类似这样,但我不想重复两次: preg_match_all($pattern,$string,$matches); $string = preg_replace($pattern,'',$string); 你是说像这样的 $string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string); 更新: 我想你想要这样的东西。。但是你现在可以看到,如果不使事情复杂化,这是不可能的(如@gnud-answer)。所
preg_match_all($pattern,$string,$matches);
$string = preg_replace($pattern,'',$string);
你是说像这样的
$string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string);
更新:
我想你想要这样的东西。。但是你现在可以看到,如果不使事情复杂化,这是不可能的(如@gnud-answer)。所以答案是否定的,你不能在一行中完成它。好的
因此,您希望在一个函数调用中捕获匹配项并进行替换。我猜您不想两次处理代价高昂的正则表达式,否则我看不出有什么好的理由让代码可读性降低
反正
你可以试试使用。比如:
class MatchReplace {
var $matches;
var $pattern;
var $replacement;
var $string;
var $matchCount;
function __construct($pattern, $replacement) {
$this->replacement = $replacement;
$this->pattern = $pattern;
}
function matchAndReplace($string) {
$this->string = $string;
var_dump($string);
var_dump($this->pattern);
return preg_replace_callback($this->pattern,
array($this, '_worker'), $string, -1, $this->matchCount);
}
function _worker($matches) {
echo "Matches:\n";
var_dump($matches);
}
}
运行示例:
echo "<pre>\n";
$m = new MatchReplace('|(abc)|', '');
echo "\nResult: \n".$m->matchAndReplace('XXXabcYYY');
echo "\n</pre>";
如果不需要复杂的替换规则(如正则表达式),则应始终使用str_replace()函数,而不是ereg_replace()或preg_replace()
这将执行所有出现的操作,并且只执行一个命令。从外观上看,您正在执行两个完全不同的操作
preg_match_all($pattern1,$string,$matches);
$result = preg_grep($pattern2, $matches);
所以你实际上什么都没有做两次。除非您在后面的某个地方使用$matches,否则如果您要执行preg_replace afterwords,那么第一行是不相关的。您的确切模式是什么?还有haystack?你能更具体一点,描述一下你想做什么吗?在你的代码中,第一行似乎是多余的。除非你以后用火柴。但是如果你想在以后使用匹配项,并且还想替换字符串,那么你需要两个regexOf,当然我稍后会使用:)除非你的正则表达式非常复杂,否则没有理由这样做。只需运行两次:第一次匹配,然后替换。像这样的正则表达式最好运行两次,所以现在您可能已经得到了答案,因为不可能在一行中完成它。:)
preg_match_all($pattern,$string,$matches); // return all the matches
$string = preg_replace($pattern,'',$string); // replace all the matches in the string
preg_match_all($pattern1,$string,$matches);
$result = preg_grep($pattern2, $matches);