I’m trying to give my client the ability to call a function that has various code snippets by inserted a short code in their WYSIWYG editor.
For example, they will write something like…
[getSnippet(1)]
This will call my getSnippet($id) php function and output the appropriate ‘chunk’.
It works when I hard code the $id like this…
echo str_replace('[getSnippet(1)]',getSnippet(1),$rowPage['sidebar_details']);
However, I really want to make the ‘1’ dynamic. I’m sort of on the right track with something like…
function getSnippet($id) {
if ($id == 1) {
echo "car";
}
}
$string = "This [getSnippet(1)] is a sentence.This is the next one.";
$regex = '#([getSnippet(\w)])#';
$string = preg_replace($regex, '. \1', $string);
//If you want to capture more than just periods, you can do:
echo preg_replace('#(\.|,|\?|!)(\w)#', '\1 \2', $string);
Not quite working 🙁
Firstly in your regex you need to add literal parentheses (the ones you have just capture
\wbut that will not match the parentheses themselves):I also escaped the square brackets, otherwise they will open a character class. Also be aware that this captures only one character for the parameter!
But I recommend you use
preg_replace_callback, with a regex like this:Note that I changed the
echoin yourgetSnippetto areturn.Within the callback
$matches[1]will contain the first captured group, which in this case is your parameter (which now allows for multiple characters). Of course, you could also adjust yougetSnippetfunction to read theidfrom the$matchesarray instead of redirecting through thereplaceCallback.But this approach here is slightly more flexible, as it allows you to redirect to multiple functions. Just as an example, if you changed the regex to
#\[(getSnippet|otherFunction)\((\w+)\)\]#then you could find two different functions, andreplaceCallbackcould find out the name of the function in$matches[1]and call the function with the parameter$matches[2]. Like this:It really depends on where you want to go with this. The important thing is, there is no way of processing an arbitrary parameter in a replacement without using
preg_replace_callback.