ChatGPT解决这个技术问题 Extra ChatGPT

删除多个空格

我从 MySQL 数据库中获取 $row['message'],我需要删除所有空格,如 \n \t 等等。

$row['message'] = "This is   a Text \n and so on \t     Text text.";

应格式化为:

$row['message'] = 'This is a Text and so on Text text.';

我试过了:

 $ro = preg_replace('/\s\s+/', ' ',$row['message']);
 echo $ro;

但它不会删除 \n\t,只会删除单个空格。谁能告诉我该怎么做?

换行符和制表符用单引号括起来,所以你想要它们文字?
我通过将其更改为双引号来修复使用 \n 和 \t 对代码 sectin 的引用。

A
Avatar

你需要:

$ro = preg_replace('/\s+/', ' ', $row['message']);

您正在使用 \s\s+ 表示空格(空格、制表符或换行符)后跟一个或多个空格。这实际上意味着用一个空格替换两个或多个空格。

您想要的是用单个空格替换一个或多个空格,因此您可以使用模式 \s\s*\s+(推荐)


他的方法比这更好:为什么要用一个空格替换一个空格?
他还希望将 \n 和 \t 替换为空格。现在他的模式与这些不匹配,比如 $x = "does\nthis\twork"; OP 希望将所有空格替换为单个空格。
@codaddict,我们如何保留 \n 并从字符串中删除所有其他多个空格和制表符?请帮我
您能否更具体地说明为什么推荐使用“\s+”?
请注意,在 PHP \s 中不包括“垂直标签”chr(11)。要包含它,您需要使用 space 字符类:[[:space:]]+ php.net/manual/en/regexp.reference.character-classes.php
u
uınbɐɥs
<?php
$str = "This is  a string       with
spaces, tabs and newlines present";

$stripped = preg_replace(array('/\s{2,}/', '/[\t\n]/'), ' ', $str);

echo $str;
echo "\n---\n";
echo "$stripped";
?>

这输出

This is  a string   with
spaces, tabs and newlines present
---
This is a string with spaces, tabs and newlines present

你是真正的救星。如果窗户越过这个,我正要跳出来。
不错,还是有用的
好吧,我从来没有想过这一点,但 12 年后它仍然运作良好!
A
Amal Murali
preg_replace('/[\s]+/mu', ' ', $var);

\s 已经包含制表符和新行,因此上面的正则表达式似乎就足够了。


这里不需要方括号,因为它们里面只有一件事。 /m 不会产生影响,因为没有 ^$ 锚点,并且 /u 不会产生任何影响,除非输入字符串不是有效的 UTF-8 (它不会影响 \s 匹配的内容,但会影响 \pZ)。
L
Lukas Liesis

简化为一个功能:

function removeWhiteSpace($text)
{
    $text = preg_replace('/[\t\n\r\0\x0B]/', '', $text);
    $text = preg_replace('/([\s])\1+/', ' ', $text);
    $text = trim($text);
    return $text;
}

基于丹尼尔奥尼尔的回答。


g
ghostdog74
$str='This is   a Text \n and so on Text text.';
print preg_replace("/[[:blank:]]+/"," ",$str);

这是最适合我的。另外,我会添加修剪以擦除字符串开头和结尾的空格
@Dziamid 你可以用 trim(preg_replace(...))
n
nickf

我无法在这里复制问题:

$x = "this    \n \t\t \n    works.";
var_dump(preg_replace('/\s\s+/', ' ', $x));
// string(11) "this works."

我不确定这是否只是转录错误,但在您的示例中,您使用的是单引号字符串。如果您有双引号字符串,\n\t 只会被视为换行符和制表符。那是:

'\n\t' != "\n\t"

编辑:正如 Codaddict 指出的那样,\s\s+ 不会替换单个制表符。我仍然不认为使用 \s+ 是一个有效的解决方案,那么如何代替:

preg_replace('/(?:\s\s+|\n|\t)/', ' ', $x);

+1,是的。对于具有大量单个空格的字符串(通常是这种情况),用空格替换空格是低效的。
@coaddict:为了测试你的假设,我编写了一个快速脚本来运行每个替换的 1000 个并检查每个替换的时间。对于字符串 '+1,True。对于具有大量单个空格的字符串(通常是这种情况),用空格替换空格是低效的。 – codaddict 2 月 24 日'10 点 13:32',一千个 \s+ preg_replace() 调用耗时 0.010547876358032 秒,一千个 (?:\s\s+|\n|\t) preg_replace() 调用耗时 0.013049125671387,使得它慢了近 30%。
您可能希望在最后一个示例中添加“\r”,因为某些计算机确实单独使用单个“\r”(Apple Mac?)
m
middus
preg_replace('/(\s\s+|\t|\n)/', ' ', $row['message']);

这会用一个空格替换所有制表符、所有换行符以及多个空格、制表符和换行符的所有组合。


\t & \n 已包含在 \s 中,因此您的正则表达式完全\s\s+ 相同,写得更好 \s{2,} 就像 @Alex Polo answer
D
Danuel O'Neal
<?php
#This should help some newbies
# REGEX NOTES FROM DANUEL
# I wrote these functions for my own php framework
# Feel Free to make it better
# If it gets more complicated than this. You need to do more software engineering/logic.
# (.)  // capture any character
# \1   // if it is followed by itself
# +    // one or more

class whitespace{

    static function remove_doublewhitespace($s = null){
           return  $ret = preg_replace('/([\s])\1+/', ' ', $s);
    }

    static function remove_whitespace($s = null){
           return $ret = preg_replace('/[\s]+/', '', $s );
    }

    static function remove_whitespace_feed( $s = null){
           return $ret = preg_replace('/[\t\n\r\0\x0B]/', '', $s);
    }

    static function smart_clean($s = null){
           return $ret = trim( self::remove_doublewhitespace( self::remove_whitespace_feed($s) ) );
    }
}
$string = " Hey   yo, what's \t\n\tthe sc\r\nen\n\tario! \n";
echo whitespace::smart_clean($string);

静态函数 remove_whitespace 是出于什么原因?您定义但从不使用它。
这些每个都有其用途,但这些都不能实现问题所要求的,即用一个替换多个连续的空格。你的“remove_doublewhitespace”只会替换多个相同的空白字符,所以它会用''替换“\n\n\n”,但它不会对“\r\n”做任何事情
h
hharek

没有 preg_replace()

$str = "This is   a Text \n and so on \t     Text text.";
$str = str_replace(["\r", "\n", "\t"], " ", $str);
while (strpos($str, "  ") !== false)
{
    $str = str_replace("  ", " ", $str);
}
echo $str;

m
matsolof

这就是我会使用的:

一个。确保使用双引号,例如:

$row['message'] = "This is   a Text \n and so on \t     Text text.";

湾。要删除多余的空格,请使用:

$ro = preg_replace('/\s+/', ' ', $row['message']); 
echo $ro;

它可能不是最快的解决方案,但我认为它需要最少的代码,并且应该可以工作。不过,我从未使用过mysql,所以我可能错了。


A
Alex Polo

您只需按如下方式运行它:

echo preg_replace('/\s{2,}/', ' ', "This is   a Text \n and so on \t     Text text."); // This is a Text and so on Text text.

C
Catalin T.

我使用这个代码和模式:

preg_replace('/\\s+/', ' ',$data)

$data = 'This is   a Text 
   and so on         Text text on multiple lines and with        whitespaces';
$data= preg_replace('/\\s+/', ' ',$data);
echo $data;

您可以在 http://writecodeonline.com/php/ 上进行测试


即使在这个查询中的 mariaDB 中,它也适用于我:SELECT search_able, REGEXP_REPLACE (search_able,"\\s+",' ') FROM book where id =260 非常感谢
B
BigBlast

事实上,如果认为你想要这样的东西:

preg_replace('/\n+|\t+|\s+/',' ',$string);

H
Heman G

这将用单个选项卡替换多个选项卡

preg_replace("/\s{2,}/", "\t", $string);

S
Shahbaz Khan

没有 preg_replace,在循环的帮助下。

<?php

$str = "This is   a Text \n and so on \t     Text text.";
$str_length = strlen($str);
$str_arr = str_split($str);
for ($i = 0; $i < $str_length; $i++) {
    if (isset($str_arr[$i + 1])
       && $str_arr[$i] == ' '
       && $str_arr[$i] == $str_arr[$i + 1]) {
       unset($str_arr[$i]);
    } 
    else {
      continue;
    }
}

 echo implode("", $str_arr) ; 

 ?>