0
我有一個腳本,它貫穿用戶輸入的文本,並用html代替標籤中包含的文本。它大多工作正常,但其中一個標籤給我帶來麻煩。如何將preg_match的多個實例替換爲不同的替換文本?
[include = someFile.php]應該加載someFile.php的內容到頁面中,[inlude = thatFile.txt]應該加載thatFile.txt。但是,如果有多個包含標記的實例,每個實例都引用不同的文件,則只用一個包含的文件替換它們。我使用的代碼是這樣的......
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);
}
}
謝謝Uby,那是我需要的信息 – Shane 2013-04-05 23:19:57
很高興幫助:) – Uby 2013-04-06 08:01:27