Question

How would I replace anything but letters and numbers with a hyphen? This would be for a slug URL where a person would type in the string they would like for their URL. The problem I’m having is people inputting symbols and many spaces which make the URL invalid.

Also, what would be a good resource to test this so that I don’t have to ask again? Thanks.

Was it helpful?

Solution

The code

$input_url = "This is only an example: do you like it?";
$slug_url = preg_replace("/[^a-zA-Z0-9]/", "-", $input_url);
print($slug_url);

will output

This-is-only-an-example--do-you-like-it-

DEMO

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top