Best code for replacing special characters and spaces with a dash for use in a URL

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’])

I am trying to have this URL:

https://www.minisgallery.com/index.php?id=7033&task=image&imageName=Chwinga%20-%20Space%20Guppy

Instead display as:

https://www.minisgallery.com/index.php?id=7033&task=image&imageName=Chwinga-Space-Guppy

Here is my code that is generating this:

echo '<a href="' . $indexPage . '?id=' . $result_mini['id'] . '&task=image&imageName=' . preg_replace('/[^a-zA-Z0-9 s]/','-',$result_mini['name']) . '" target="_blank">';

How can I eliminate the %20’s from displaying?

How can I replace the spaces with dashes – I thought the reference of “s” in the preg_replace is supposed to do that?

Are you familiar with the PHP urldecode function? If you can use the result of that then it is much easier.

I’m not at all familiar with that, but I will read more about it. Thank you.

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.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.