Click here to Skip to main content
15,905,776 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I have stored the product names in database with spaces. For example Bike 86, Washing Machine etc.
After using urlencode URL comes to browser as below
http://www.example.com/product.php?productname=Washing+Machine

But I want to get it such like
http://www.example.com/prodcut.php?productname=Washing-Machine


How can I change the urlencode function that it encode the space into hyphen(-) not into "+" sign.

If it is not possible with urlencode then how can I do that.


Note: Please give me some other solution rather than str_replace();
Posted
Updated 1-Nov-11 2:52am
v3

1 solution

It's a bit more complicated than that.

The + in the URL has a special meaning. The web server will interpret it as a space. These days it is considered best practices to encode space in its hex form e.g. http://www.example.com/product.php?productname=Washing%20Machine which follows RFC 3986 standards, but the + will be around for a long time and is still supported by all browsers and servers.

You want to replace the + with -. You can't do that (even with str_replace) because whereas + means the same thing as space, - doesn't. It just means -.

It is still possible though, but not in PHP. You will need to configure the web server to rewrite any - signs that it sees to spaces before it looks for the file. On Apache you would most likely create a file called .htaccess in the root directory of your site and it would contain something like:

RewriteEngine on

# Replace the minus character in incoming URLs with a space.
RewriteRule ^([^-]*)-([^-]*-.*) $1%20$2 [N] 
RewriteRule ^([^-]*)-([^-]*)$ /$1%20-$2 [L] 
 
Share this answer
 
Comments
rashidfarooq 1-Nov-11 10:54am    
Thanks for answering. Let me Try that.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900