📜  删除符号和空格 php (1)

📅  最后修改于: 2023-12-03 15:07:15.980000             🧑  作者: Mango

删除符号和空格 PHP

在开发过程中,我们经常需要处理一些字符串,并且需要删除一些符号和空格,以便于后续的处理。在 PHP 中,我们可以使用一些内置的函数来实现这个目标。

删除符号
rtrim()函数

rtrim() 函数可以删除右侧的指定字符。

$str = "Hello, World!";
$str = rtrim($str, "!");
echo $str; // 输出 Hello, World
ltrim()函数

ltrim() 函数可以删除左侧指定字符。

$str = "   Hello, World!   ";
$str = ltrim($str);
echo $str; // 输出 Hello, World!   
trim()函数

trim() 函数可以删除两侧指定字符。

$str = "   Hello, World!   ";
$str = trim($str);
echo $str; // 输出 Hello, World!
str_replace()函数

str_replace() 函数可以删除字符串中的指定字符。

$str = "Hello, World!";
$str = str_replace(",", "", $str);
echo $str; // 输出 Hello World!
删除空格
rtrim()函数

rtrim() 函数可以删除右侧的空格。

$str = "Hello, World! ";
$str = rtrim($str);
echo $str; // 输出 Hello, World!
ltrim()函数

ltrim() 函数可以删除左侧的空格。

$str = " Hello, World!";
$str = ltrim($str);
echo $str; // 输出 Hello, World!
trim()函数

trim() 函数可以删除两侧的空格。

$str = " Hello, World! ";
$str = trim($str);
echo $str; // 输出 Hello, World!
preg_replace()函数

preg_replace() 函数可以删除字符串中的空格。

$str = " Hello, World! ";
$str = preg_replace("/\s+/", "", $str);
echo $str; // 输出 Hello,World!

以上就是删除符号和空格的几种方法,选用适合自己的方法即可。