PHP str_replace 用下划线替换空格
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/12704613/
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
PHP str_replace replace spaces with underscores
提问by Gisheri
Is there a reason that I'm not seeing, why this doesn't work?
有没有我没有看到的原因,为什么这不起作用?
$string = $someLongUserGeneratedString;
$replaced = str_replace(' ', '_', $string);
echo $replaced;
The output still includes spaces... Any ideas would be awesome
输出仍然包含空格......任何想法都会很棒
回答by Laurent Brieu
I'll suggest that you use this as it will check for both single and multiple occurrence of white space (as suggested by Lucas Green).
我建议您使用它,因为它会检查单个和多个出现的空白(如 Lucas Green 所建议的)。
$journalName = preg_replace('/\s+/', '_', $journalName);
instead of:
代替:
$journalName = str_replace(' ', '_', $journalName);
回答by Lucas Green
Try this instead:
试试这个:
$journalName = preg_replace('/\s+/', '_', $journalName);
Explanation: you are most likely seeing whitespace, not just plain spaces (there is a difference).
说明:您最有可能看到空格,而不仅仅是普通空格(有区别)。
回答by Ravi Patel
For one matched character replace, use str_replace:
对于一个匹配的字符替换,使用str_replace:
$string = str_replace(' ', '_', $string);
For all matched character replace, use preg_replace:
对于所有匹配的字符替换,使用preg_replace:
$string = preg_replace('/\s+/', '_', $string);
回答by IsaacP
Try this instead:
试试这个:
$journalName = str_replace(' ', '_', $journalName);
to remove white space
去除空白

