如何在每个单词后加减号? [重复]

This question already has an answer here:

I am working on youtube video feed, and I want to transform each video title to seotitle.

I have a string like so: 'Kings Of Leon - Use Somebody'

and I want it to be like this: 'Kings-Of-Leon-Use-Somebody'.

I have try this code:

$seotitle=str_replace(' ','-',$video['title']['$t']);

but I get this 'Kings-Of-Leon-Use---Somebody'

What is a good way to handle with extra spaces and minus?

</div>

Try this one:

$string = 'Kings Of Leon - Use Somebody';

// first replace anything but letters with space
$string = preg_replace('/[^a-zA-Z]/', ' ', $string);

// then replace consecutive spaces with hypen
$string = preg_replace('/[ ]+/', '-', trim($string));

See inline comments for detail.

A simple regex to do what you want is:

preg_replace('|[ -]+|', '-', $seotitle);

You can use the same function to replace the ' - ' with ' ' like this:

$seotitle_temp=str_replace(' - ', ' ', 'Kings Of Leon - Use Somebody'); 
$seotitle_temp=str_replace(' ', '-', 'Kings Of Leon - Use Somebody');

Then you will go clear.

Try This :

//string assign to variable
$string = 'Kings Of Leon - Use Somebody';
//Removes whitespace or other predefined characters from the right side of a string
$string = ltrim($string);
// Removes whitespace or other predefined characters from both sides of a string
$string = rtrim($string);
// str replace methods
$string = str_replace(" ", "-", $string);
// RemoveSpecial Character
$string = preg_replace("/[^A-Za-z0-9\-]/", "",$string);
// Remove Multiple -
$string = preg_replace('/-+/', '-',$string);