2009-10-08 44 views
1

这样的事情,但我并不想这样做2次:如何在PHP中匹配并替换一个满口?

preg_match_all($pattern,$string,$matches); 
$string = preg_replace($pattern,'',$string); 
+0

什么是你的精确模式?干草堆? – powtac 2009-10-08 11:36:42

+0

你能更具体一点,并且实际描述你正在尝试做什么? – James 2009-10-08 11:52:54

+0

在你的代码中,第一行似乎是多余的。除非你以后使用火柴。但是,如果你想以后用火柴,也想更换琴弦,那么你需要两个正则表达式 – andho 2009-10-08 12:21:44

回答

-1

你的意思是这样的吗?

$string = preg_replace(preg_match_all($pattern,$string,$matches),'',$string); 

更新:

我是这么认为的,你想是这样的..但现在你可以看到,它不可能没有事情复杂(如@gnud答案)。所以答案是否定的,你不能在一行中完成。

+3

将不起作用,preg_match_all返回一个int不匹配。 – James 2009-10-08 11:37:54

+0

不工作,但似乎他得到了我的意思。 – Misier 2009-10-08 11:44:06

+0

所以可能你现在得到了答案,它不可能在一行中完成。 :) – TigerTiger 2009-10-08 12:35:11

1

好吧,

所以你想捕获匹配,并在一次函数调用中替换。我猜你不想处理一个昂贵的正则表达式两次,否则我看不出有什么理由让你的代码不易读。

反正

你可以尝试使用preg_replace_callback()。喜欢的东西:

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>"; 

输出:

string(9) "XXXabcYYY" 
string(7) "|(abc)|" 
Matches: 
array(2) { 
    [0]=> 
    string(3) "abc" 
    [1]=> 
    string(3) "abc" 
} 

Result: 
XXXYYY 
+0

这是太复杂了,我甚至会喜欢它的两倍.. – Misier 2009-10-08 12:04:50

+0

除非你的正则表达式是疯狂的复杂,​​没有充分的理由这样做。只需运行两次:首先匹配,然后替换。 – gnud 2009-10-08 12:10:55

+0

这样的正则表达式最好运行两次 – andho 2009-10-08 12:19:16

0

如果你不需要花哨更换的规则(比如正则表达式),你应该使用str_replace函数( )函数而不是ereg_replace()或preg_replace()。

http://uk.php.net/str_replace

这将尽一切的发生,只有1个命令。

0

通过它你正在做2个完全独立的东西的样子。

preg_match_all($pattern,$string,$matches); // return all the matches 
$string = preg_replace($pattern,'',$string); // replace all the matches in the string 

所以你实际上并没有做任何事情两次。除非你使用$匹配,否则第一行是无关紧要的,如果你打算继续使用preg_replace后缀。

0
preg_match_all($pattern1,$string,$matches); 
$result = preg_grep($pattern2, $matches);