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

时间:2015-09-22 20:25:17

标签: php regex preg-replace

我有一个这样的字符串:

(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 个答案:

答案 0 :(得分:4)

你实际上距离正确的结果并不远:

  1. /之前逃离link(否则,它将被视为正则表达式分隔符并完全破坏您的正则表达式)
  2. 使用单引号声明正则表达式(或者您必须使用双反斜杠来转义正则表达式元字符)
  3. .*?周围添加一个捕获组(以便稍后可以使用$1参考)
  4. 请勿使用U因为它会使.*?贪婪
  5. 以下是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