3

just wondering what's the best approach for template String replace.

preg_replace('/{%(\S+)%}/', 'bill', $tableOutput);

With the preg_replace, if there are lots of string needs to be replace, the function will be called many times depend on the number of string needs to be replace. Just wondering if there is a way can look though string once and replace accordingly?

Thanks

hakre
  • 193,403
  • 52
  • 435
  • 836
Bill
  • 17,872
  • 19
  • 83
  • 131
  • 1
    Is [this](http://stackoverflow.com/questions/8846225/php-function-that-replaces-texts-with-variables/8846257#8846257) what you want to do? – Jon Jan 17 '12 at 02:06
  • 1
    As per [the fine PHP manual](http://php.net/manual/en/function.preg-replace.php), you can supply `preg_replace` with array arguments. So, no. It won't be called many times. –  Jan 17 '12 at 02:08
  • Jon you are the answer i am seeking for. Thanks very much – Bill Jan 17 '12 at 02:14

1 Answers1

4

Use the array syntax of preg_replace...?

preg_replace(array('/pattern1/', '/pattern2/'), array('replacement1', ...), ...)
deceze
  • 510,633
  • 85
  • 743
  • 889
  • But can you actually find the replace string and match with replacement. eg {%itemname%}, find the {%itemname%} and doing a match in the array['itemname'], and replace with the value? – Bill Jan 17 '12 at 02:09
  • 1
    Yes, you can use lookahead and lookbehind then replace the match. `(?<=\){%item%}(?=\<\/td\>)`. If you need finer control using capturing groups you can capture the tag contents and replace on that using `preg_replace_callback`. – Aram Kocharyan Jan 17 '12 at 02:18
  • 1
    A simpler way would be to just use the backreference $1 in the replacement string of `preg_replace` however. – Aram Kocharyan Jan 17 '12 at 02:20
  • 1
    Aram u r pro, Thanks for the answer – Bill Jan 17 '12 at 02:21