如何用破折号-php替换字符串中的空格
我想用单破折号替换出现的任何空格,如果有多个空格,那么应该只用一个破折号替换 例如:如何用破折号-php替换字符串中的空格,php,regex,Php,Regex,我想用单破折号替换出现的任何空格,如果有多个空格,那么应该只用一个破折号替换 例如: $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"
$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"
我试过这个:
$string = "this is testing string\n\n\nxyz\t\t\tabc";
echo preg_replace('![\s+|\t+|\n+]!', "-" , $string);
但是问题是它用单破折号替换了每个空格你把模式写错了,你真正需要的是这个
[\s]+
看看这个:
$string = "this is testing string\n\n\nxyz\t\t\tabc";
echo preg_replace('![\s]+!', "-" , $string);
preg\u replace(“~\s+~”、“-”、$string)
应该可以正常工作,因为\s
匹配所有空白。内部[…]
+
匹配一个文本+
\t
和\n
包含在\s
中,/ui
标志在此无效。
echo preg_replace('/(\s|\t|\n)+/ui', "-" , $string);