1

I'm trying to implement short codes on my website to make publishing easier. What i got so far look like this:

$text = "[button]Hello[button] [input]holololo[input]";
$shortcodes = Array( 'button' => '<button>{content}</button>', 'input' => '<input type="text" value="{content}" />' );
$text = preg_replace_callback('(\[([a-z]+?)\](.+?)\[\\\1\])', function ($matches){ 
   if ($shortcodes[$matches[1]]){ 
            return str_replace('{content}', $matches[2], $shortcodes[$matches[1]]); 
   }else{
     return $matches[0]; 
   } 
}, $text);
echo $text;

What i want this to echo is: <button>Hello</button> <input type="text" value="holololo" />

But instead it just echo's out: [button]Hello[button] [input]holololo[input]

What am I doing wrong?

1 Answer 1

1

Two things. First, your regex is like this:

'(\[([a-z]+?)\](.+?)\[\\\1\])'

You don't want to escape the slash before the 1, otherwise you are literally searching for "\1" rather than the backreference. So that should be:

'(\[([a-z]+?)\](.+?)\[\1\])'

Also:

function ($matches) { 

You try to refer to $shortcodes in your function. However, that is defined outside the function, so it has no access to it. You must explicitly pass any non-global variables to a function. When dealing with an anonymous function like this, use the use instruction, so your function definition should look like this:

function ($matches) use ($shortcodes) {

Making those two simple changes gave me this output:

<button>Hello</button>
<input type="text" value="holololo">
Sign up to request clarification or add additional context in comments.

2 Comments

It won't show just a button if i only have the tags like this: [button][button], and i'm not that good in php, could you help me?
@Murillio4 That's actually not a PHP issue, just a slight change in your regex: (.+?) means one or more of any character. If you change it to (.*?) that means zero or more of any character. In other words, that allows it to match nothing at all. Note, however, that'll give you a button with no text.

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.