How to remove spaces from lines in PHP?

When working with text, you often have to format it. This is necessary for correct display and easy readability. This is necessary if the user enters some information and makes mistakes: instead of one space, indicates two, at the beginning puts a tab. There are several ways to remove spaces in PHP.

Trim ()

The Trim function searches for excess characters at the beginning of a line or at the end. It:

  • regular space;
  • tabulation
  • line break character.

It is written in this form:

string trim ( string $str [, string $character_mask = " \t\n\r\0\x0B" ] )
      
      



$ str is the string to be processed, and $ character_mask is the extra characters. $ character_mask is an optional attribute.

Preg_replace

.

Trim () function in PCP




mixed preg_replace ( mixed $pattern , mixed $replacement , mixed $subject [, int $limit = -1 [, int &$count ]] )
      
      



  1. $pattern – .
  2. $replacement – .
  3. $subject – .
  4. $limit – .

$pattern $replacement . .

Str_replace()

PHP str_replace(). .





mixed str_replace ( mixed $search , mixed $replace , mixed $subject [, int &$count ] )
      
      



preg_replace().

  1. $search – , .
  2. $replace – .
  3. $subject – , .
  4. $count .
<?php

//  <body text='black'>

$bodytag = str_replace("%body%", "black", "<body text='%body%'>");

// : Hll Wrld f PHP

$vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O", "U");

$onlyconsonants = str_replace($vowels, "", "Hello World of PHP");

// : You should eat pizza, beer, and ice cream every day

$phrase = "You should eat fruits, vegetables, and fiber every day.";

$healthy = array("fruits", "vegetables", "fiber");

$yummy = array("pizza", "beer", "ice cream");

$newphrase = str_replace($healthy, $yummy, $phrase);

// : 2

$str = str_replace("ll", "", "good golly miss molly!", $count);

echo $count;

?>
      
      



, .

YP PHP




, , . – , .

$text1 = "     ";
      
      



, . , PHP, .

1. .

explode(“ ”, $text1)
      
      



. , , , .

2. :

$array = [" “, “”, “”, “ “, “ "]
      
      



3. :

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



To search for one or more spaces, use the regular expression / \ s + /. All matches found are replaced by the string. '' Search is carried out in the variable $ text1.

4. As a result, we get a string with the correct number of spaces, which is easily perceived by the user.




All Articles