This article shows how you can have [shortcodes] in brackets [/shortcodes] and replace them with your own content using preg_replace in PHP.
One of our customers required some text decoration in a text field of a third-party Wordpress plugin where no provision was available to write HTML in the contents of that field. We cheated a bit by adding bracketed shortcodes.
Suppose you have a text like this:
## End result (could be)
This is a text where this part is [important]very important[/important].
[sidenote]This remark is a sidenote to this important text[/sidenote].
[obsolete]This is obsolete and maybe removed soon[/obsolete]
[underlined]For your eyes only[/underlined]
Here we have three bracketed shortcodes:
- important
- sidenote
- obsolete
- underlined
But you can have your own shortcodes as long as they are not in conflict with any shortcode plugins you are using wherever you want to use them (like: Wordpress, October CMS or any other).
What we want to achieve
We want the string that is returned or echoed to contain:
<h2>End result (could be)</h2>
This is a text where this part is <strong>very important</strong>.
<i>This remark is a sidenote to this important text</i>.
<strike>This is obsolete and maybe removed soon</strike>
<u>For your eyes only</u>
PHP preg_replace
With the PHP preg_replace, not favored by everyone, function you can search for a (regular expression) pattern and when found replace it with something else. Just like str_replace, but preg_replace is able to replace content based on the result of a regular expression. Just as we will see in the sample below.
Link
...
$html = textDecoration($html);
echo $html;
....
function textDecoration($html)
{
/**
* see: https://www.php.net/manual/en/function.preg-replace.php
*/
$patterns = [
'/\[(important)\](.*?)\[\/\1\]?/',
'/\[(sidenote)\](.*?)\[\/\1\]?/',
'/\[(obsolete)\](.*?)\[\/\1\]?/'
];
$replacements = [
'<i>$2</i>',
'<strong>$2</strong>',
'<strike>$2</strike>'
];
return preg_replace($patterns, $replacements, $html);
}
Let's have a look at the pattern structure:
'/\[(important)\](.*?)\[\/\1\]?/'
There are 2 groups in this structure
- (important) $1
- (.*?) $2
The indicators $1 and $2 can be used in the $replacements array.
So the replacement structure (HTML) is now:
'<i>$2</i>'
Please notice that you can have the patterns and replacements as an array, where every pattern position corresponds with its replacement position.
The variable is $2 and not $1, for all replacements would be the name of the shortcode itself. The variable relates to the group. As said earlier the structures have 2 groups encapsulated by '()' in the regular expression.
End result (could be)
This is a text where this part is very important.
This remark is a sidenote to this important text.
This is obsolete and maybe removed soon
For your eyes only
your email address will not be published. required fields are marked *