urlencode in preg_replace

女生的网名这么多〃 提交于 2019-12-22 09:47:33

问题


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

i want to encode url, but how can I do that?

can i use urlencode() function in preg_replace?, something like that,

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

do you have any idea about encoding url in preg_replace?


回答1:


You can use preg_replace_callback, which allows you to produce the replacement string by running code directly:

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

If you use PHP >= 5.3, you can make the above a bit less painful:

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


来源:https://stackoverflow.com/questions/6315999/urlencode-in-preg-replace

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!