使用PHP创建短码将HTML打开和关闭标签添加到字符串的方法



我不确定我是否在措辞,因为它不是完全的折叠代码。

我要实现的是创建一个在我的字符串中找到替代星号的函数。但是我需要先替换。

$srting = 'Create personalised *tasty treats*';

我需要考虑它的多种用途,例如下面的此字符串...

$srting = 'Create personalised *tasty treats* and branded *promotional products*';

第一个*将被开放的<span class="d-inline-block">

替换

第二个*将被</span>

替换

,周期再次重复,以便在字符串中更多使用*

我不确定最有效的方法是解决这个问题吗?任何想法都会非常感谢。


使用可接受的答案更新了下面的工作功能。

public static function word_break_fix($string) {
   $newString = preg_replace('/\*([^*]*)\*/s', '<span class="d-inline-block">\1</span>', $string);
   return $newString;
}

只需使用preg_replace捕获两个星号之间的所有内容即可。您可以从替换数字中引用一个捕获组。

preg_replace('/\*([^*]*)\*/s', '<span class="d-inline-block">\1</span>', $subject)

https://regex101.com/r/i7fm8x/1/

请注意,在PHP中,正则表达式是由字符串构建的,因此您可以在使用字符串文字时再次逃脱正则持平和后斜线。

是的,这绝对是理想的适合于Regex!

用于更换标签,类似的东西很好:

<?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;

这是Regex101的链接,因此您可以查看并了解REGEX的工作原理:https://regex101.com/r/pyctzu/1

但要按照您的指定注入HTML,请尝试以下操作:

<?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;

最新更新