Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

urlencode in preg_replace

$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?

like image 774
Okan Kocyigit Avatar asked Aug 31 '25 23:08

Okan Kocyigit


1 Answers

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);
like image 69
Jon Avatar answered Sep 03 '25 13:09

Jon