Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何用破折号-php替换字符串中的空格_Php_Regex - Fatal编程技术网

如何用破折号-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);