-1

I am trying to understand how to create a custom parser for shortcodes in PHP, but I need directions on which php function (or maybe even php library) to use.

For example, I have a string in this format:

Hello {user.name}, your CODE is {user.code}

I have in advance prepared email templates with custom 'shortcodes' (user_name, id, adress and so on). I'd like to dynamically check if string has shortcodes and replaced all shortcodes on real data from database.

6
  • 2
    Use str_replace() Commented Aug 12, 2021 at 9:36
  • Michel, how to know how many paraments pass to str_replace() ? I have different templates with different amount shortcodes name. Commented Aug 12, 2021 at 9:53
  • 1
    Please read the the manual about str_replace() @Michel linked to which shows you exactly how to use it. Then at least make some attempts. If you want more help, just google on your title and look at one of the many guides/examples you'll find (that's not related to Wordpress). I found plenty when I just did that. meta.stackoverflow.com/questions/261592/… Commented Aug 12, 2021 at 9:56
  • Magnus Eriksson, thank you very much. I read manual. I do not understand some things.. my templates data is dynamic.. how to understand how many paraments I should pass to function? At one time it could be 2 shortcodes but in another time 10 shortcodes. For me it is not understandable. Commented Aug 12, 2021 at 10:22
  • 1
    Use a regex like this to extract the shortcodes, then retrieve from database, then str_replace Commented Aug 12, 2021 at 10:30

1 Answer 1

1

First off, I would rather call them "placeholders" (a string to be replaced) than "shortcodes" (a short code that executes a larger code).

I'm assuming that you have a fixed list of possible placeholders though?

You can pass the complete list of placeholders and their replacements:

$placeholders = [
    '{user.name}',
    '{user.code}',
    '{user.foo}',
    ...
];

// Change the replacements to be the correct values from where you have them
$replacements = [
    $user->name,
    $user->code,
    $user->foo,
    ....
];

$string = str_replace($placeholders, $replacements, $string);

If any of the placeholders in the list doesn't exist in the string, it will just be ignored.

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

2 Comments

Yes, I have fixed list of possible placeholders, but their replacements always different.
@roman - "but their replacements always different" - I get that the values are different, but the source for those values, (like variables/functions) still has to be the same, right, which is what you set in the replacement array (as I've showed you in the code above)? Or are you replacing the placeholders with random values from random variables/functions? That would make zero sense.

Your Answer

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