簡體   English   中英

如何用不同的替換文本替換preg_match匹配項的多個實例?

[英]How do you replace multiple instances of a preg_match matches with different replacement text?

我有一個腳本,該腳本通過用戶輸入的文本運行,並用html替換標記中包含的文本。 它通常可以正常工作,但是其中一個標簽給我帶來了麻煩。

[include = someFile.php]應該將someFile.php的內容加載到頁面中,[inlude = thatFile.txt]應該將thatFile.txt加載。 但是,當include標記有多個實例時,每個實例都引用不同的文件,它將僅用其中一個包含文件替換它們。 我正在使用的代碼是這樣的...

if (preg_match ("/\[include=(.+?)\]/", $text, $matches)) {
  foreach ($matches as $match) {
    $match = preg_replace("/\[include=/", "", $match);
    $match = preg_replace("/\]/", "", $match);
    $include = $match;
    $file_contents = file_get_contents($include);
    $text = preg_replace("/\[include=(.+?)\]/", "$file_contents", $text);
  }
}

foreach循環的最后一行似乎是用它在當前標簽中找到的內容替換匹配標簽的每個實例,但是我不知道該怎么做。 任何建議表示贊賞!

編輯:感謝Uby,我進行了以下更改,現在可以使用。

if (preg_match_all ("/\[include=(.+?)\]/", $text, $matches)) {

    foreach ($matches[0] as $match) {
        $file = preg_replace("/\[include=/", "", $match);
        $file = preg_replace("/\]/", "", $file);
        $file_contents = file_get_contents($file);
        $text = str_replace("$match", "$file_contents", $text);
    }

}

preg_match()僅會匹配一次,在您的情況下,您應該使用preg_match_all() (請參閱文檔http://php.net/manual/zh/function.preg-match-all.php

仔細閱讀文檔,您的循環將無法正常工作。

暫無
暫無

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

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