如何用dash - php代替字符串?

时间:2022-07-07 16:50:17

I want to replace any occurrence of whitespaces with single dash , if there was more than one whitespace then it should be replaced with one dash only

我想用单破折号替换任何出现的空格,如果有多个空格,则应该用一个破折号替换

for example :

例如:

$string = "testing string"              //should be "testing-string"
$string = "testing      string"         //should be "testing-string"
$string = "testing\t\t\n\n  string"     //should be "testing-string"

I had tried this :

我曾经尝试过:

$string = "this is   testing  string\n\n\nxyz\t\t\tabc";
echo preg_replace('![\s+|\t+|\n+]!', "-" , $string);

but the problem it replace every single whitespace with single dash

但是问题是它用一个破折号替换了每个空格

2 个解决方案

#1


2  

You have written the pattern wrong, what you really need is this [\s]+

你把模式写错了,你真正需要的是这个[\s]+

Check this out:

看看这个:

$string = "this is   testing  string\n\n\nxyz\t\t\tabc";
echo preg_replace('![\s]+!', "-" , $string);

#2


0  

echo preg_replace('/(\s|\t|\n)+/ui', "-" , $string);

#1


2  

You have written the pattern wrong, what you really need is this [\s]+

你把模式写错了,你真正需要的是这个[\s]+

Check this out:

看看这个:

$string = "this is   testing  string\n\n\nxyz\t\t\tabc";
echo preg_replace('![\s]+!', "-" , $string);

#2


0  

echo preg_replace('/(\s|\t|\n)+/ui', "-" , $string);