Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

str_replace

Tags:

regex

url

php

slug

Current code only replace the spaces to dash (-)

$url = str_replace(' ','-',$url);

I want only letters, numbers and dash (-) allowed on the URL.

Let me know the tricks.

like image 983
wow Avatar asked Jan 29 '26 01:01

wow


1 Answers

Do you want this for generating slug?

Then you can do something like this:

$slugified = preg_replace('/[^-a-z0-9]+/i', '-', strtolower(trim($url)));

It will strip leading and trailing whitespace first, convert the string to lowercase, then replace all non-word characters (not a-z, 0-9 or -) with a single -

A    Beautiful *# Day will become a-beautiful-day

Remove strtolower() if you don't mind uppercase letters in the slug.

like image 187
Imran Avatar answered Jan 31 '26 14:01

Imran



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!