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 ^^)

Link to comment
Share on other sites

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().

 

 

Link to comment
Share on other sites

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

Link to comment
Share on other sites

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)

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.