skip to Main Content

I am trying to encode a phrase in order to pass it inside a URL. Currently it works fine with basic words, where spaces are replaces with dashes.

<a href="./'.str_replace(' ', '-', preg_replace("/[^A-Za-z0-9- ]/", '', $phrase)).'">

It produces something like:


On the page that this URL takes me I am able to replace the dashes with spaces and query my db for this phrase.

The problem I have is if the phrase contains apostrophe. My current script removes it. Is there any way to preserve it or replace with some URL-friendly character to accommodate something like?

this is bob's page



  1. If you want to allow another character , you have to add it to this section: ^A-Za-z0-9- so if for example you wish to allow ' the regex will be [^A-Za-z0-9-' ]

    Login or Signup to reply.
  2. There is a PHP standard library function urlencode() to encode non-alphanumeric characters with %Xxx where xx is the hex value of the character.

    If the limitations of that conversion (&, ©, £, etc.), are not acceptable, see rawurlencode().

    Login or Signup to reply.
  3. If you only need to replace all the apostrophes ('), then you can replace it with the URL-encoded character %27:

    str_replace("'", "%20", $url);


    If you want to replace all URL-non-safe character, use a built-in function like in @wallyk’s answer. It’s much simpler.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top