簡體   English   中英

如何在PHP中進行匹配和替換?

[英]How to match and replace in a mouthful with PHP?

像這樣,但我不想做兩次:

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

好,

因此,您想捕獲一個匹配項,並在一個函數調用中進行替換。 我猜您不想重復處理一個昂貴的正則表達式,否則我看不出有充分的理由讓您的代碼可讀性降低。

無論如何,

您可以嘗試使用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

如果不需要花哨的替換規則(如正則表達式),則應始終使用str_replace()函數而不是ereg_replace()或preg_replace()。

http://uk.php.net/str_replace

這將執行所有操作,並且僅執行1條命令。

從外觀上看,您正在做2個完全獨立的事情。

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

因此,您實際上沒有做任何事情兩次。 除非您在該行的更下方使用$ matches,否則無論如何您都要進行preg_replace后綴,第一行是無關緊要的。

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

你的意思是這樣的嗎?

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

更新:

我以為您想要這樣的東西..但是您現在可以看到,如果不復雜的話(例如@gnud答案)是不可能的。 因此,答案是否定的,您不能一站式完成。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM