如何去除 PHP 变量中的空格?

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

How can strip whitespaces in PHP's variable?

phpstringwhitespace

提问by Léo Léopold Hertz ??

I know this commentPHP.net. I would like to have a similar tool like trfor PHP such that I can run simply

我知道这个评论PHP.net。我想要一个类似trPHP 的工具,这样我就可以简单地运行

tr -d " " ""

I run unsuccessfully the function php_strip_whitespaceby

我运行不成功的功能php_strip_whitespace通过

$tags_trimmed = php_strip_whitespace($tags);

I run the regex function also unsuccessfully

我运行正则表达式函数也没有成功

$tags_trimmed = preg_replace(" ", "", $tags);

采纳答案by ppostma1

A regular expression does not account for UTF-8 characters by default. The \smeta-character only accounts for the original latin set. Therefore, the following command only removes tabs, spaces, carriage returns and new lines

默认情况下,正则表达式不考虑 UTF-8 字符。该\s元字符只占原来的拉丁语集。因此,以下命令仅删除制表符、空格、回车符和换行符

// http://stackoverflow.com/a/1279798/54964
$str=preg_replace('/\s+/', '', $str);

With UTF-8 becoming mainstream this expression will more frequently fail/halt when it reaches the new utf-8 characters, leaving white spaces behind that the \scannot account for.

随着 UTF-8 成为主流,这个表达式在到达新的 utf-8 字符时将更频繁地失败/停止,留下\s无法解释的空格。

To deal with the new types of white spaces introduced in unicode/utf-8, a more extensive string is required to match and removed modern white space.

为了处理 unicode/utf-8 中引入的新型空格,需要更广泛的字符串来匹配和删除现代空格。

Because regular expressions by default do not recognize multi-byte characters, only a delimited meta string can be used to identify them, to prevent the byte segments from being alters in other utf-8 characters (\x80in the quad set could replace all \x80sub-bytes in smart quotes)

因为正则表达式默认不识别多字节字符,所以只能用一个分隔的元字符串来识别它们,以防止字节段被其他utf-8字符改变(\x80在quad set中可以替换所有\x80子字节在智能引号中)

$cleanedstr = preg_replace(
    "/(\t|\n|\v|\f|\r| |\xC2\x85|\xc2\xa0|\xe1\xa0\x8e|\xe2\x80[\x80-\x8D]|\xe2\x80\xa8|\xe2\x80\xa9|\xe2\x80\xaF|\xe2\x81\x9f|\xe2\x81\xa0|\xe3\x80\x80|\xef\xbb\xbf)+/",
    "_",
    $str
);

This accounts for and removes tabs, newlines, vertical tabs, formfeeds, carriage returns, spaces, and additionally from here:

这会考虑并删除制表符、换行符、垂直制表符、换页符、回车符、空格,以及从这里额外的:

nextline, non-breaking spaces, mongolian vowel separator, [en quad, em quad, en space, em space, three-per-em space, four-per-em space, six-per-em space, figure space, punctuation space, thin space, hair space, zero width space, zero width non-joiner, zero width joiner], line separator, paragraph separator, narrow no-break space, medium mathematical space, word joiner, ideographical space, and the zero width non-breaking space.

下一行,不间断空格,蒙古元音分隔符,[en 四元组,em 四元组,en 空格,em 空格,每个 em 三个空格,每个 em 空格四个,每个 em 空格六个,数字空格,标点空格,细空间,头发空间,零宽度空间,零宽度非连接器,零宽度连接器],行分隔符,段落分隔符,窄不间断空间,中等数学空间,单词连接器,表意空间和零宽度非打破空间。

Many of these wreak havoc in xml files when exported from automated tools or sites which foul up text searches, recognition, and can be pasted invisibly into PHP source code which causes the parser to jump to next command(paragraph and line separators) which causes lines of code to be skipped resulting in intermittent, unexplained errors that we have begun referring to as "textually transmitted diseases"

当从自动化工具或站点导出时,其中的许多会在 xml 文件中造成严重破坏,这些工具或站点会破坏文本搜索、识别,并且可以无形地粘贴到 PHP 源代码中,从而导致解析器跳转到导致行的下一个命令(段落和行分隔符)要跳过的代码导致间歇性的、无法解释的错误,我们开始将其称为“文本传播疾病”

[Its not safe to copy and paste from the web anymore. Use a character scanner to protect your code. lol]

[从网络复制和粘贴不再安全。使用字符扫描器来保护您的代码。哈哈]

回答by Paul Dixon

To strip anywhitespace, you can use a regular expression

要去除任何空格,您可以使用正则表达式

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

See also this answerfor something which can handle whitespace in UTF-8 strings.

另请参阅此答案,了解可以处理 UTF-8 字符串中的空格的内容。

回答by trante

Sometimes you would need to delete consecutive white spaces. You can do it like this:

有时您需要删除连续的空格。你可以这样做:

$str = "My   name    is";
$str = preg_replace('/\s\s+/', ' ', $str);

Output:

输出:

My name is

回答by Tyler Carter

$string = str_replace(" ", "", $string);

I believe preg_replace would be looking for something like [:space:]

我相信 preg_replace 会寻找类似的东西 [:space:]

回答by Kumar

You can use trim function from php to trim both sides (left and right)

您可以使用 php 中的修剪功能来修剪两侧(左右)

 trim($yourinputdata," ");

Or

或者

trim($yourinputdata);

You can also use

你也可以使用

ltrim() - Removes whitespace or other predefined characters from the left side of a string
rtrim() - Removes whitespace or other predefined characters from the right side of a string

System: PHP 4,5,7
Docs: http://php.net/manual/en/function.trim.php

系统:PHP 4,5,7
文档:http://php.net/manual/en/function.trim.php

回答by camomileCase

If you want to remove all whitespaces everywhere from $tags why not just:

如果您想从 $tags 中删除所有空格,为什么不只是:

str_replace(' ', '', $tags);

If you want to remove new lines and such that would require a bit more...

如果您想删除新行,则需要更多...

回答by micropro.cz

Any possible option is to use custom file wrapper for simulating variables as files. You can achieve it by using this:

任何可能的选择是使用自定义文件包装器将变量模拟为文件。你可以通过使用它来实现它:

1) First of all, register your wrapper (only once in file, use it like session_start()):

1) 首先,注册您的包装器(仅在文件中一次,像 session_start() 一样使用它):

stream_wrapper_register('var', VarWrapper);

2) Then define your wrapper class (it is really fast written, not completely correct, but it works):

2)然后定义你的包装类(它写得非常快,不完全正确,但它有效):

class VarWrapper {
  protected $pos = 0;
  protected $content;
  public function stream_open($path, $mode, $options, &$opened_path) {
    $varname = substr($path, 6);
    global $$varname;
    $this->content = $$varname;
    return true;
  }
  public function stream_read($count) {
    $s = substr($this->content, $this->pos, $count);
    $this->pos += $count;
    return $s;
  }
  public function stream_stat() {
    $f = fopen(__file__, 'rb');
    $a = fstat($f);
    fclose($f);
    if (isset($a[7])) $a[7] = strlen($this->content);
    return $a;
  }
}

3) Then use any file function with your wrapper on var:// protocol (you can use it for include, require etc. too):

3) 然后在 var:// 协议上使用带有包装器的任何文件函数(您也可以将它用于包含、要求等):

global $__myVar;
$__myVar = 'Enter tags here';
$data = php_strip_whitespace('var://__myVar');

Note: Don't forget to have your variable in global scope (like global $__myVar)

注意:不要忘记将变量置于全局范围内(例如 global $__myVar)

回答by Abdulla Nilam

You can do it by using ereg_replace

您可以使用 ereg_replace

 $str = 'This Is New Method Ever';
 $newstr = ereg_replace([[:space:]])+', '',  trim($str)):
 echo $newstr
 // Result - ThisIsNewMethodEver

回答by samehanwar

you also use preg_replace_callbackfunction . and this function is identical to its sibling preg_replaceexcept for it can take a callback function which gives you more control on how you manipulate your output.

您还可以使用preg_replace_callbackfunction 。并且此函数与其兄弟函数相同,preg_replace只是它可以采用回调函数,这使您可以更好地控制如何操作输出。

$str = "this is a   string";

echo preg_replace_callback(
        '/\s+/',
        function ($matches) {
            return "";
        },
        $str
      );

回答by S. Mert

$string = trim(preg_replace('/\s+/','',$string));