urlencode in preg_replace

2019-05-24 13:16发布

问题:

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