How to Remove Whitespace from String in PHP

PHP chop() function returns a string after removing the specified characters from an end. The chop() function is an alias of rtrim() function.

How to Remove Whitespace from String in PHP

To remove whitespace from a string in PHP, use the chop() function. The chop() is a built-in PHP string function that removes whitespaces or other predefined characters from the right end of the string. The chop() function removes any other specified characters from the end of the string.

Syntax

The syntax of the PHP String chop() function is following.

string chop($string, $character)

Parameters

The $string argument is which is needed to be checked.

The $character argument specifies the character needed to be removed from a given string. If the parameter is not specified, then NULL, tab, newline, vertical tab, carriage return, and ordinary white space are removed automatically.

See the following characters are removed if a charlist parameter is empty:

  1. “\0” – NULL
  2. “\t” – tab
  3. “\n” – newline
  4. “\x0B” – vertical tab
  5. “\r” – carriage return
  6. ” ” – ordinary white space

Return value

The return type of the chop() function is a string.

Example

See the code example.

<?php

$site = 'AppDividend';
echo chop($site, 'end');

See the output.

➜  pro php app.php
AppDivi                                                                         
➜  pro

Passing no parameters

Since no character parameter is mentioned in the code below, the newlines will automatically be removed from a given string.

<?php

$statement = "Hello Millie! \n nice to meet you \n \n"; 
echo chop($statement);

See the output.

➜  pro php app.php
Hello Millie!
 nice to meet you                                                               
➜  pro

How to remove the last character from string in PHP

To remove the last character from a string in PHP, use the chop() function.

<?php

$entrepreneur = "MillieBobbyBrown"; 
echo chop($entrepreneur, 'n');

See the output.

➜  pro php app.php
MillieBobbyBrow                                                                 
➜  pro

You can see that the last character “n” from the string is removed.

Okay, let’s use the rtrim() function.

rtrim() in PHP

The rtrim() is a built-in PHP function that removes the characters from the right side of a string.

<?php

$entrepreneur = "MillieBobbyBrown"; 
echo rtrim($entrepreneur, 'n');

See the output.

➜  pro php app.php
MillieBobbyBrow                                                                 
➜  pro

That’s it for PHP chop() function.

Recommended Posts

PHP money_format()

PHP number_format()

PHP unset()

PHP strstr()

PHP Password Hashing Functions API

Leave a Comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.