php - How do you replace multiple instances of a preg_match matches with different replacement text? -
i have script runs through text input user , replaces text contained in tags html. works fine 1 of tags giving me trouble.
[include=somefile.php] should load contents of somefile.php page, [inlude=thatfile.txt] should load thatfile.txt. however, when there multiple instances of include tag, each 1 referring different files, replacing them 1 of included files. code using this...
if (preg_match ("/\[include=(.+?)\]/", $text, $matches)) { foreach ($matches $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); } }
the last line of foreach loop seems replacing every instance of matched tags whatever finds in current tag don't know it. advice appreciated!
edit: uby made following changes , works now.
if (preg_match_all ("/\[include=(.+?)\]/", $text, $matches)) { foreach ($matches[0] $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()
match 1 occurrence, in case should use preg_match_all()
(see documentation http://php.net/manual/en/function.preg-match-all.php)
read documentation, loop wouldn't work this.
Comments
Post a Comment