Jump to content

[SOLVED] need to use rawurlencode inside the preg_replace


asmith

Recommended Posts

Hi,

 

I use this code to replace the words in the array, with links :

 

<?php
preg_replace('~('.implode('|', explode(',',$keywords)).')~','<a href="search.php?keyword=$0">$0</a>',$content))
?>

 

it works fine for english characters. But for other characters, I have to rawurlencode() them.

 

I did the changes like this : (or some similar ways) :

<?php
preg_replace('~('.implode('|', explode(',',$keywords)).')~','<a href="search.php?keyword='.rawurlencode('$0').'">$0</a>',$content))
?>

 

But no success.

How can I use rawurlencode inside that function?

 

edit : its makes the link like  keyword=$0 , and if O remove the single quotes around it, it gives me error. (That's obvious ^^)

Thanks for the reply.

 

I think with your solution, I will lose the $0 as of the link name too :

 

<a href="search.php?keyword=$0">$0</a>

 

 

I need the red one to be rawurlencode, but the blue one without it.

I guess you code makes both rawurlencode().

 

 

i like this way better:

<?php
  foreach(explode(',',$keywords) as $keyword){
    $content = str_ireplace($keyword,'<a href="search.php?keyword='.rawurlencode($keyword).'">'.$keyword.'</a>',$content);
  }
?>

 

but if you want to stick with preg:

<?php
preg_replace('~('.implode('|', explode(',',$keywords)).')~e',"'<a href=\"search.php?keyword='.rawurlencode('\\0').'\">\\0</a>'",$content);
?>

not sure, and the answer will probably be dependent on how big $keywords and $content is. but, I will say two things:

 

-the foreach() code is WAY easier to read

-the preg code will fail if a keyword has a ~ or a ) in it (and I image some other characters too)

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.