用 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=''></a>", $return);

你其实离正确的结果不远了:

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

这里是my suggestion:

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

PHP code

$re = '/\(link\)(.*?)\(\/link\)/'; 
$str = "(link)there is link1(/link), (link)there is link2(/link)"; 
$subst = "<a href=''></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);

another IDEONE demo