Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

replace all combinations of non-alphanumeric characters

Tags:

php

I need to to create url from various strings.
So trying to replace all non-alphanumeric characters and all of their combinations - with a hyphen character (-)

$string = "blue - sky";
$string = preg_replace("/[^A-Za-z0-9 ]/", '-', $string);
echo $string;  

result - blue---sky
expected - blue-sky.

like image 772
qadenza Avatar asked Nov 20 '25 05:11

qadenza


1 Answers

use the + sign to replace more than one character with one replacement character:

string = preg_replace("/[^A-Za-z0-9]+/", '-', $string);
like image 152
Jens Avatar answered Nov 22 '25 19:11

Jens



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!