如何在PHP变量中删除空格?

时间:2009-08-14 19:36:30

标签: php string whitespace

我知道这个comment PHP.net。 我希望有一个像PHP tr这样的工具,以便我可以简单地运行

tr -d " " ""

我通过

运行php_strip_whitespace函数失败了
$tags_trimmed = php_strip_whitespace($tags);

我运行正则表达式功能也失败了

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

14 个答案:

答案 0 :(得分:133)

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

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

另请参阅this answer以获取可处理UTF-8字符串空格的内容。

答案 1 :(得分:37)

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

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

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

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

因为默认情况下正则表达式不能识别多字节字符,所以只能使用分隔的元字符串来识别它们,以防止字节段在其他utf-8字符中更改(\x80四元组可以替换智能引号中的所有\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
);

这会占用并删除标签,换行符,垂直标签,换页,回车,空格以及here

  

nextline,非破坏空间,蒙古语元音分隔符,[en quad,em quad,en space,em space,三个每em空间,四个每个空间,六个每个空间,数字空间,标点符号空间,稀疏空间,毛发空间,零宽度空间,零宽度非连接器,零宽度连接器],线分隔符,段落分隔符,窄不间断空间,中等数学空间,字连接器,表意空间和零宽度不间断的空间。

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

[再也不能安全地从网上复制和粘贴了。使用字符扫描程序来保护您的代码。洛尔]

答案 2 :(得分:26)

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

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

输出:

My name is

答案 3 :(得分:12)

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

我相信preg_replace会寻找像[:space:]

这样的东西

答案 4 :(得分:7)

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

 trim($yourinputdata," ");

或者

trim($yourinputdata);

您也可以使用

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

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

答案 5 :(得分:5)

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

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

如果你想删除新的行,那就需要更多......

答案 6 :(得分:2)

任何可能的选择是使用自定义文件包装器将变量模拟为文件。您可以使用以下方法实现它:

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

stream_wrapper_register('var', VarWrapper);

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)然后在var:// protocol上使用你的包装器的任何文件函数(你可以将它用于include,require等):

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

注意:不要忘记将变量放在全局范围内(如全局$ __ myVar)

答案 7 :(得分:1)

您还使用preg_replace_callback功能。这个函数与它的兄弟preg_replace相同,除了它可以采用回调函数,它可以让你更好地控制你如何操作输出。

$str = "this is a   string";

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

答案 8 :(得分:1)

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

答案 9 :(得分:1)

这是旧帖子,但此处未列出最短答案,所以我现在添加它

strtr($str,[' '=>'']);

另一种常见的“剥这只猫”的方法是使用爆炸和内爆

implode('',explode(' ', $str));

答案 10 :(得分:0)

旧帖子可以这样做:

if(!function_exists('strim')) :
function strim($str,$charlist=" ",$option=0){
    $return='';
    if(is_string($str))
    {
        // Translate HTML entities
        $return = str_replace(" "," ",$str);
        $return = strtr($return, array_flip(get_html_translation_table(HTML_ENTITIES, ENT_QUOTES)));
        // Choose trim option
        switch($option)
        {
            // Strip whitespace (and other characters) from the begin and end of string
            default:
            case 0:
                $return = trim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the begin of string 
            case 1:
                $return = ltrim($return,$charlist);
            break;
            // Strip whitespace (and other characters) from the end of string 
            case 2:
                $return = rtrim($return,$charlist);
            break;

        }
    }
    return $return;
}
endif;

标准trim()函数在出现HTML实体时可能会出现问题。这就是为什么我写了“Super Trim”函数用来处理这个问题的原因,你也可以选择从字符串的开头,结尾或者一边修剪。

答案 11 :(得分:0)

从整个字符串中删除空格的一种简单方法是使用explode函数,并使用for循环打印整个字符串。

 $text = $_POST['string'];
            $a=explode(" ", $text);
            $count=count($a);
            for($i=0;$i<$count; $i++){

                echo $a[$i];
            }

答案 12 :(得分:0)

\ s的regex参数与UTF-8 multybyte字符串不兼容。

此PHP RegEx是我编写的,它使用基于PCRE(与Perl兼容的正则表达式)的参数代替UTF-8字符串来解决此问题:

outer

-示例用法-

之前:

function remove_utf8_whitespace($string) { 
   return preg_replace('/\h+/u','',preg_replace('/\R+/u','',$string)); 
}

之后:

$string = " this is a test \n and another test\n\r\t ok! \n";

echo $string;

 this is a test
 and another test
         ok!

echo strlen($string); // result: 43

PCRE参数列表

来源:https://www.rexegg.com/regex-quickstart.html

$string = remove_utf8_whitespace($string);

echo $string;

thisisatestandanothertestok!

echo strlen($string); // result: 28

答案 13 :(得分:0)

标签形式有一些特殊类型的空格。 您需要使用

$str=strip_tags($str);

删除冗余标签,错误标签,然后首先获取正常字符串。

并使用

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

这对我有用。