php preg_replace 所有空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/8175655/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
preg_replace all spaces
提问by user740521
I'm trying to replace all spaces with underscores and the following is not working:
我正在尝试用下划线替换所有空格,但以下内容不起作用:
$id = "aa aa";
echo $id;
preg_replace('/\s+/', '_', $id);
echo $id;
prints
印刷
aa aaaa aa
回答by Mark Byers
The function preg_replace
doesn't modify the string in-place. It returns a new string with the result of the replacement. You should assign the result of the call back to the $id
variable:
该函数preg_replace
不会就地修改字符串。它返回一个带有替换结果的新字符串。您应该将回调的结果分配给$id
变量:
$id = preg_replace('/\s+/', '_', $id);
回答by Clive
I think str_replace()
might be more appropriate here:
我认为str_replace()
这里可能更合适:
$id = "aa aa";
$id = str_replace(' ', '_', $id);
echo $id;
回答by Martin.
You have forgotten to assign the result of preg_replace
into your $id
您忘记将结果分配preg_replace
到您的$id
$id = preg_replace('/\s+/', '_', $id);
回答by Mahesh Mohan
Sometimes, in linux/unix environment,
有时,在 linux/unix 环境中,
$strippedId = preg_replace('/\h/u', '', $id);
Try this as well.
也试试这个。
回答by web_developer
We need to replace the space in the string "aa aa" with '_' (underscore). The \s+ is used to match multiple spaces. The output will be "aa_aa"
我们需要用'_'(下划线)替换字符串“aa aa”中的空格。\s+ 用于匹配多个空格。输出将是“aa_aa”
<?php
$id = "aa aa";
$new_id = preg_replace('/\s+/', '_', $id);
echo $new_id;
?>