I am a new coder and am trying to display a name, as part of a URL.
I believe I have to use the preg_replace() php function, but I cannot find a good source for explaining the syntax of this. I want to convert all special characters and spaces to a dash. Could someone please help me out with the syntax for this?
I have tried using this, and I think it is partially working, but I am still doing something wrong. An ampersand in the name is being converted to a dash, but spaces are not. Also, I’m getting a lot of %20 in the URL.
Here is the code I used:
preg_replace(‘/[^a-zA-Z0-9 s]/’,‘-’,$str’])
There is a function for both urldecode() and urlencode().
Encode will turn your string into one suitable for a URL, no need for any regex. PHP has plenty of built in functions for common web tasks. It’s just a case of knowing about them.