繁体   English   中英

用preg_replace(php)替换两个标签之间的内容

[英]Replace content between two tags with preg_replace (php)

我有一个像这样的字符串:

(link)there is link1(/link), (link)there is link2(/link)

现在,我想设置看起来像这样的链接:

<a href='there is link1'>there is link1</a>, <a href='there is link2'>there is link2</a>

我尝试使用preg_replace,但结果是一个错误( Unknown modifier 'l'

preg_replace("/\\(link\\).*?\\(/link\\)/U", "<a href='$1'>$1</a>", $return);

您实际上离正确的结果不远:

  1. 转义/之前的link (否则,它将被视为正则表达式定界符并完全破坏您的正则表达式)
  2. 使用单引号声明正则表达式(否则,必须使用双反斜杠转义正则表达式元字符)
  3. .*?周围添加一个捕获组.*? (以便您以后可以使用$1引用)
  4. 不要使用U因为它会产生.*? 贪婪

这是我的建议

\(link\)(.*?)\(\/link\)

PHP代码

$re = '/\(link\)(.*?)\(\/link\)/'; 
$str = "(link)there is link1(/link), (link)there is link2(/link)"; 
$subst = "<a href='$1'>$1</a>"; 
$result = preg_replace($re, $subst, $str);
echo $result;

也可以使用urlencode() href参数,可以使用preg_replace_callback函数并在其中使用$m[1] (捕获组值):

$result = preg_replace_callback($re, function ($m) {
    return "<a href=" . urlencode($m[1]) . "'>" . $m[1] . "</a>";
  }, $str);

观看另一个IDEONE演示

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM