urgcode在preg_replace中

时间:2011-06-11 12:46:39

标签: php preg-replace urlencode

$str = preg_replace("'\(look: (.{1,80})\)'Ui",
             "(look: <a href=\"dict.php?process=word&q=\\1\">\\1</a>)",$str);

我想编码网址,但我该怎么做呢?

我可以在preg_replace中使用urlencode()函数吗?

$str = preg_replace("'\(look: (.{1,80})\)'Ui",
            "(look: <a href=\"dict.php?process=word&q=\\1\">\\1</a>)",$str);

你对preg_replace中的url编码有什么想法吗?

1 个答案:

答案 0 :(得分:8)

您可以使用preg_replace_callback,它允许您通过直接运行代码来生成替换字符串:

$str = preg_replace_callback(
    "'\(look: (.{1,80})\)'Ui",
    create_function(
        '$matches',
        'return \'(look: <a href="dict.php?process=word&q='.urlencode($matches[1]).'">'.
          $matches[1].'</a>)\';'
    ),
    $str);

如果你使用PHP&gt; = 5.3,你可以减少上面的痛苦:

$str = preg_replace_callback(
    "'\(look: (.{1,80})\)'Ui",
    function($matches) {
        return "(look: <a href=\"dict.php?process=word&q=".urlencode($matches[1])."\">".
               $matches[1]."</a>)";
    },
    $str);