Reputation: 5088
I'm not sure if I am phrasing this right as it's not exactly shortcodes.
What I am trying to achieve is to create a function that find a replaces asterisks in my strings. But I need to alternate first and second replace.
$srting = 'Create personalised *tasty treats*';
I need to account for multiple uses of it, for example like this string below...
$srting = 'Create personalised *tasty treats* and branded *promotional products*';
The first *
will be replaced with a opening <span class="d-inline-block">
The second *
will be replaced with a closing </span>
And the the cycle repeats again for any more uses of *
in the string.
I'm not sure what the most efficient way is to approach this, is this something that could be done with regex? Any ideas would be great thanks.
Updated working function below using accepted answer.
public static function word_break_fix($string) {
$newString = preg_replace('/\\*([^*]*)\\*/s', '<span class="d-inline-block">\\1</span>', $string);
return $newString;
}
Upvotes: 3
Views: 105
Reputation: 6682
Just use preg_replace
capturing everything between two asterisks. You can reference a capturing group from the replacement by a backslashed number.
preg_replace('/\\*([^*]*)\\*/s', '<span class="d-inline-block">\\1</span>', $subject)
https://regex101.com/r/i7fm8X/1/
Note that in PHP regular expressions are built by strings, thus you escape characters once for the regex and the backslash is escaped again when using string literals.
Upvotes: 1
Reputation: 2963
Yes, this is absolutely something ideally suited for regex!
For tag replacement, something like this works well:
<?php
$string = 'Create personalised *tasty treats* and branded *promotional products* *tasty treats*';
$replace = preg_replace_callback("/(\\*[a-zA-Z\\s]*\\*)/m", function ($matches) {
switch($matches[0])
{
case "*tasty treats*":
return "Chocolate!";
case "*promotional products*":
return "DRINK COCA COLA!";
}
return $matches[0];
}, $string);
echo $replace;
Here's a link to Regex101 so you can see and learn how the regex works: https://regex101.com/r/pyCTZU/1
But to inject HTML as you specified, try this:
<?php
$string = 'Create personalised *tasty treats* and branded *promotional products* *tasty treats*';
$replace = preg_replace_callback("/(\\*[a-zA-Z\\s]*\\*)/m", function ($matches) {
return "<span class=\"d-inline-block\">".substr($matches[0], 1, strlen($matches[0]) - 2)."</span>";
}, $string);
echo $replace;
Upvotes: 0