gpt4 book ai didi

PHP preg_replace 修改

转载 作者:行者123 更新时间:2023-12-04 15:14:02 29 4
gpt4 key购买 nike

我有一个表达式[text][id]应替换为链接 <a href='id'>text</a>

解决方案是( id 是整数)

$s = preg_replace("/\[([^\]]+)(\]*)\]\[([0-9]+)\]/","<a href='$3'>$1$2</a>",$string);

但是,在某些情况下(并非总是!)表达式可能如下所示

[text][id][type]

在这种情况下应替换为 <a href='id' class='type'>text</a>

想法?

最佳答案

使用 preg_replace_callback 的解决方案功能:

$str = 'some text [hello][1] some text [there][2][news]';  // exemplary string

$result = preg_replace_callback('/\[([^][]+)\]\[([^][]+)\](?:\[([^][]+)\])?/',function($m){
$cls = (isset($m[3]))? " class='{$m[3]}'" : ""; // considering `class` attribute
return "<a href='{$m[2]}'$cls>{$m[1]}</a>";
},$str);

print_r($result);

输出(作为网页源代码):

some text <a href='1'>hello</a> some text <a href='2' class='news'>there</a>

  • (?:\[([^][]+)\])? - 考虑可选的第三个捕获组(对于 class 属性值)

关于PHP preg_replace 修改,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44489052/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com