本文将介绍在 PHP 中从一个字符串中去掉所有空格的方法。剥离所有空格是指从一个给定的字符串中删除所有空格。使用 str_replace() 函数使用 preg_replace() 函数在 PHP 中...

本文将介绍在 PHP 中从一个字符串中去掉所有空格的方法。剥离所有空格是指从一个给定的字符串中删除所有空格。
使用 str_replace() 函数
使用 preg_replace() 函数
str_replace() 函数去掉所有空格我们使用内置函数 str_replace() 来替换字符串或数组中的子字符串。替换后的字符串作为一个参数传递。使用该函数的正确语法如下。
str_replace($searchString, $replaceString, $originalString, $count);
内置函数 str_replace() 有四个参数。它的详细参数如下
参数 | 说明 | |
|---|---|---|
| 强制 | 它是我们要查找和替换的子字符串或数组 |
| 强制 | 它是我们要放在 |
| 强制 | 它是原始的字符串,我们想从中找到一个子字符串或一个字符来替换。 |
| 可选 | 它告诉人们对 |
这个函数返回所有替换后得到的最终字符串。
下面的程序显示了我们如何使用 str_replace() 函数从给定的字符串中删除所有空格。
<?php
$searchString = " ";
$replaceString = "";
$originalString = "This is a programming tutorial";
$outputString = str_replace($searchString, $replaceString, $originalString);
echo("The original string is: $originalString \n");
echo("The string without spaces is: $outputString");
?>
我们已经传递了一个空格字符作为 $searchString 和一个空字符串作为 $replaceString。输出将是没有空格的字符串。
输出:
The original string is: This is a programming tutorial
The string without spaces is: Thisisaprogrammingtutorial
现在,如果我们传入 $count 参数,函数将告诉我们这个字符串的替换次数。
<?php
$searchString = " ";
$replaceString = "";
$originalString = "This is a programming tutorial";
$outputString = str_replace($searchString, $replaceString, $originalString, $count);
echo("The original string is: $originalString \n");
echo("The string without spaces is: $outputString \n");
echo("The number of replacement operations is: $count");
?>
输出:
The original string is: This is a programming tutorial
The string without spaces is: Thisisaprogrammingtutorial
The number of replacement operations is: 4
preg_replace() 函数去除所有空格在 PHP 中,我们也可以使用 preg_replace() 函数来删除字符串中的所有空格。这个函数不仅可以删除空格字符,还可以删除字符串中的制表符。使用这个函数的正确语法如下。
preg_replace($regexPattern, $replacementVar, $original, $limit, $count)
函数 preg_replace() 接受五个参数. 它的详细参数如下
参数 | 说明 | |
|---|---|---|
| 强制 | 它是我们将在原始字符串或数组中搜索的模式 |
| 强制 | 它是我们用来替换搜索值的字符串或数组 |
| 强制 | 它是一个字符串或数组,我们要从其中找到值并替换它。 |
| 可选 | 这个参数限制了替换的数量 |
| 可选 | 这个参数告诉了我们对原始字符串或数组进行替换的总次数 |
我们将使用模式 /\s+/ 来查找空格。从字符串中删除空格的程序如下。
<?php
$searchString = " ";
$replaceString = "";
$originalString = "This is a programming tutorial";
$outputString = preg_replace('/\s+/', '', $originalString);
echo("The original string is: $originalString \n");
echo("The string without spaces is: $outputString \n");
?>
输出:
The original string is: This is a programming tutorial
The string without spaces is: Thisisaprogrammingtutorial
我们知道这个字符串的总替换次数是 4,现在我们将限制替换次数。
<?php
$searchString = " ";
$replaceString = "";
$limit = 2;
$originalString = "This is a programming tutorial";
$outputString = preg_replace('/\s+/', '', $originalString,$limit);
echo("The original string is: $originalString \n");
echo("The string without spaces is: $outputString \n");
?>
输出:
The original string is: This is a programming tutorial
The string without spaces is: Thisisa programming tutorial
注意,现在只有两个替换。