【问题标题】:Replace content between two tags with preg_replace (php)用 preg_replace (php) 替换两个标签之间的内容
【发布时间】:2015-09-23 05:06:28
【问题描述】:

我有一个这样的字符串:

(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);

【问题讨论】:

  • 你需要转义斜线
  • 但我用“\”或?转义了斜线

标签: php regex preg-replace


【解决方案1】:

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

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

这里是my suggestion

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

还有PHP code

$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);

another IDEONE demo

【讨论】:

  • 是否可以对href参数中的$1进行urlencode()?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-09-29
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多