1

Just a simple question. I have a contact form stored in a function because it's just easier to call it on the pages I want it to have.

Now to extend usability, I want to search for {contactform} using str_replace.

Example:

function contactform(){
  // bunch of inputs
}

$wysiwyg = str_replace('{contactform}', contactform(), $wysiwyg);

So basically, if {contactform} is found. Replace it with the output of contactform.

Now I know that I can run the function before the replace and store its output in a variable, and then replace it with that same variable. But I'm interested to know if there is a better method than the one I have in mind.

Thanks

1
  • If the {contactform} doesn't appear most of the time it's better to use preg_replace_callback as suggested by @jedwards. If it's always there, your current code makes most sense. Commented Apr 25, 2012 at 8:22

4 Answers 4

2

To answer your question, you could use PCRE and preg_replace_callback and then either modify your contactform() function or create a wrapper that accepts the matches.

I think your idea of running the function once and storing it in a variable makes more sense though.

Sign up to request clarification or add additional context in comments.

Comments

1

Your method is fine, I would set it as a $var if you are planning to use the contents of contactform() more than once.

It might pay to use http://php.net/strpos to check if {contact_form} exists before running the str_replace function.

You could try both ways, and if your server support it, benchmark:

<?php echo 'Memory Usage: '. (!function_exists('memory_get_usage') ? '0' : round(memory_get_usage()/1024/1024, 2)) .'MB'; ?>

Comments

0

you may want to have a look at php's call_user_func() more information here http://php.net/call_user_func

$wysiwyg = 'Some string and {contactform}';

$find = '{contactform}'; 

strpos($wysiwyg, $find) ? call_user_func($find) : '';

Comments

0

Yes, there is: Write one yourself. (Unless there already is one, which is always hard to be sure in PHP; see my next point.)

Ah, there it is: preg_replace_callback(). Of course, it's one of the three regex libraries and as such, does not do simple string manipulation.

Anyway, my point is: Do not follow PHP's [non-]design guidelines. Write your own multibyte-safe string substitution function with a callback, and do not use call_user_func().

Comments

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.