How to Remove Whitespace Characters from a String in PHP?

How to Remove Whitespace Characters from a String in PHP?

  • PHP
  • 1 min read

Here is a PHP program example to remove the whitespace characters from a string.

There is a predefined function trim(), which is used to remove the whitespace characters(whitespace characters are defined by PHP to be space, tab, newline, carriage return, NULL, vertical tab characters).

Here is an example of removing spaces from a string " welcome to India".

<html>
<body>
<?php
$a=" welcome to India";
$b=trim($a);
echo $b;
?>
</body>
</html>

Output: welcome to India

Now we will give another example of removing whitespace characters from a string " welcome to India. Delhi is the capital of India ";

<html>
<body>
<?php
$a=" welcome to India
.Delhi is the capital of India ";//string is containg spaces,tabs,newline
$b=trim($a);
echo $b;
?>
</body>
</html>

Output: welcome to India. Delhi is the capital of India

See also: