I replace all spaces with hyphens in my script like this:
$final = str_replace(' ','-',$final); The - is the only thing I replace.
What I'm replacing are Band Name - Song Name
So in this case, if I had something like:
Metallica - Hero of the Day
I end up with:
Metallica---Hero-of-the-Day
Notice the 3 ---
there?
Can you suggest an elegant way of ending up with just one -
instead of 3.
I can keep doing str_replace until it's done, but that doesn't see right.
Use the replace() method to replace spaces with dashes in a string, e.g. str. replace(/\s+/g, '-') . The replace method will return a new string, where each space is replaced by a dash.
Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.
Use a regular expression changing multiple spaces or hyphens with one hyphen:
$final = preg_replace('#[ -]+#', '-', $text);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With