【问题标题】:Moving shortcode content into attribute using preg_replace()使用 preg_replace() 将短代码内容移动到属性中
【发布时间】:2018-10-04 08:51:28
【问题描述】:

我正在使用以下内容来替换短代码的名称:

$content = '[title type="1"]Test[/title]';
$pattern = '#\[title(.*)(.*?)\[/title\]#i';
$replace = '[new_title$1[/new_title]';
echo preg_replace($pattern, $replace, $content);

这可以很好地改变这个:

[title type="1"]Test[/title]

到这里:

[new_title type="1"]Test[/new_title]

但我正在尝试将标签之间的文本移动到一个属性中,并使其像这样自动关闭:

[new_title type="1" title="Test"]

【问题讨论】:

标签: php regex string preg-replace


【解决方案1】:

你可以使用

$content = "[title type=\"1\"]Test[/title] [title]Test2[/title]\n [title type=\"6\"]Test With\nNewline 3[/title]";
$pattern = '#\[title(\s.*?)?](.*?)\[/title]#is';
$replace = '[new_title$1 title="$2"]';
echo preg_replace($pattern, $replace, $content);

this PHP demothis regex demo。如果您不想匹配带有换行符的标题,请删除使 . 匹配换行符的 s 修饰符。

模式详情

  • \[title - [title 子字符串
  • (\s.*?)? - 一个可选的捕获组,匹配 1 次或 0 次
    • \s - 任何空格
    • .*? - 任何 0+ 个字符,尽可能少
  • ] - 一个 ] 字符
  • (.*?) - 捕获组 #2:任何 0+ 个字符,尽可能少
  • \[/title] - [/title] 子字符串。

【讨论】:

    【解决方案2】:

    使用/\[(\w+)([^\]]+)](\w+).*/ 作为preg_replace() 中的模式。在模式([^\]]+) 中选择除] 之外的所有字符。

    $newContent = preg_replace("/\[(\w+)([^\]]+)](\w+).*/", '[new_title$2 title="$3"]', $content)
    

    demo查看结果

    【讨论】:

    • 使用这个正则表达式 不做任何解释它不会为 OP 提供理解的答案。
    • 谢谢,但我正在尝试将此 [title type="1"]Test[/title] 更改为此 [new_title type="1" title="Test"],请注意“title”更改为“new_title”,上面的 Wiktor Stribiżew 和 revo 的答案是正确的
    • @TheBobster Fiexed
    • .* 匹配结束标记之后的所有内容,即[/title] [description]...。您可能希望用显式结束标记替换该点星以避免这种情况。 \w+ 匹配的不仅仅是 title 标签。
    • @revo 有问题,[description] 不存在,我尝试提供简单的模式但是你的想法使模式更长
    猜你喜欢
    • 2014-01-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-06-30
    • 1970-01-01
    • 2020-12-13
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多