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:
/this-is-my-phase
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
3
Answers
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-' ]
There is a PHP standard library function
urlencode()
to encode non-alphanumeric characters with%Xxx
wherexx
is the hex value of the character.If the limitations of that conversion (&, ©, £, etc.), are not acceptable, see
rawurlencode()
.If you only need to replace all the apostrophes (
'
), then you can replace it with the URL-encoded character%27
:EDIT
If you want to replace all URL-non-safe character, use a built-in function like in @wallyk’s answer. It’s much simpler.