php 用下划线替换空格

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/6431051/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 00:21:53  来源:igfitidea点击:

Replacing Spaces with Underscores

php

提问by alex

I have a PHP Script that users will enter a name like: Alex_Newton,

我有一个PHP脚本,用户将输入一个名称,如:Alex_Newton

However, some users will use a space rather than an underscore, so my question is:

但是,有些用户会使用空格而不是下划线,所以我的问题是:

How do I auto-replace spaces with Underscores in PHP?

如何在 PHP 中用下划线自动替换空格?

回答by Tim Fountain

$name = str_replace(' ', '_', $name);

回答by aksu

As of others have explained how to do it using str_replace, you can also use regex to achieve this.

由于其他人已经解释了如何使用str_replace,您也可以使用正则表达式来实现这一点。

$name = preg_replace('/\s+/', '_', $name);

回答by anubhava

Use str_replacefunction of PHP.

使用PHP 的str_replace函数。

Something like:

就像是:

$str = str_replace(' ', '_', $str);

回答by webspy

Call http://php.net/str_replace: $input = str_replace(' ', '_', $input);

调用http://php.net/str_replace$input = str_replace(' ', '_', $input);

回答by Niklas

Use str_replace:

使用str_replace

str_replace(" ","_","Alex Newton");

回答by blakroku

You can also do this to prevent the words from beginning or ending with underscores like _words_more_words_, This would avoid beginning and ending with white spaces.

您也可以这样做以防止单词以下划线开头或结尾,例如 _words_more_words_,这将避免以空格开头和结尾。

$trimmed = trim($string); // Trims both ends
$convert = str_replace('', '_', $trimmed);

回答by Fil

I used like this

我是这样用的

$option = trim($option);
$option = str_replace(' ', '_', $option);

回答by jmmaguigad

This is part of my code which makes spaces into underscores for naming my files:

这是我的代码的一部分,它使空格变成下划线以命名我的文件:

$file = basename($_FILES['upload']['name']);
$file = str_replace(' ','_',$file);

回答by Thoracius Appotite

Strtrreplaces single characters instead of strings, so it's a good solution for this example. Supposedly strtris faster than str_replace(but for this use case they're both immeasurably fast).

Strtr替换单个字符而不是字符串,因此这是本示例的一个很好的解决方案。据说strtrstr_replace(但对于这个用例,它们都快得无法估量)。

echo strtr('Alex Newton',' ','_');
//outputs: Alex_Newton