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

3
  • 1
    Is this what you want to do? Commented Jan 17, 2012 at 2:06
  • 1
    As per the fine PHP manual, you can supply preg_replace with array arguments. So, no. It won't be called many times. Commented Jan 17, 2012 at 2:08
  • Jon you are the answer i am seeking for. Thanks very much Commented Jan 17, 2012 at 2:14

1 Answer 1

4

Use the array syntax of preg_replace...?

preg_replace(array('/pattern1/', '/pattern2/'), array('replacement1', ...), ...)
Sign up to request clarification or add additional context in comments.

4 Comments

But can you actually find the replace string and match with replacement. eg <td>{%itemname%}</td>, find the {%itemname%} and doing a match in the array['itemname'], and replace with the value?
Yes, you can use lookahead and lookbehind then replace the match. (?<=\<td\>){%item%}(?=\<\/td\>). If you need finer control using capturing groups you can capture the tag contents and replace on that using preg_replace_callback.
A simpler way would be to just use the backreference $1 in the replacement string of preg_replace however.
Aram u r pro, Thanks for the answer

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.