Php trim whitespace around edges. How to remove spaces from strings in PHP? Example of finding and replacing spaces

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, he indicates two spaces, and puts a tab at the beginning. There are several ways to remove spaces in PHP.

Trim()

The Trim function looks for extra characters at the beginning or end of a string. This:

  • 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 being processed, and $character_mask is the extra characters. $character_mask is an optional attribute.

Preg_replace

A function for searching and replacing characters using a regular expression.

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

  1. $pattern - the pattern you are looking for.
  2. $replacement - characters to replace.
  3. $subject - the object being processed.
  4. $limit - number of replacements made.

$pattern and $replacement can be arrays. In this case, replacement is made in accordance with the indexes.

Str_replace()

You can remove spaces from a string in PHP using the str_replace() method. It replaces all occurrences of the search string with the replacement string.

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

Used as a simplified preg_replace() method.

  1. $search - the value to be found.
  2. $replace - the string to be replaced.
  3. $subject - the object in which the search and replace is performed.
  4. $count sets the number of replacements.
$bodytag = str_replace("%body%", "black", " "); // assigns: Hll Wrld f PHP $vowels = array("a", "e", "i", "o", "u", "A", "E", "I", "O ", "U"); $onlyconsonants = str_replace($vowels, "", "Hello World of PHP"); // assigns: 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); // assigns: 2 $str = str_replace("ll", "", "good golly miss molly!", $count); echo $count; ?>

Example of finding and replacing spaces

These functions apply in most situations, even more complex ones.

For example, the user has entered some data that will later be printed on the screen. To improve the readability and perception of the text as a whole, this information needs to be processed - remove repeated spaces, replace them with single ones.

$text1 = "Long text with extra spaces";

In this case, you can see that there are two and three spaces between the words. The procedure for removing spaces in PHP is as follows.

1. First you need to turn a string into an array of strings using a function.

Explode(“ ”, $text1)​

A single space is used as a delimiter. This way, body parts that are not separate elements of the array will contain one less space.

2. The result is an array of strings like this:

$array = ["Long", "voluminous", "text", "with", "extra spaces"]​

3. Each element is processed by a function:

Preg_replace("/\s+/", " ", $text1)​

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

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

Good evening, recently we touched a little on the topic of passwords and their secure storage, namely, we studied the hashing function. Today we will continue the topic of passwords and their storage a little, and we will study the functions with which you can remove spaces from the beginning and end of a string. And here are the passwords and removing spaces from a string, you tell me? Firstly, this function, of course, does not relate specifically to passwords, but only works with strings, and I said about passwords only as its application. Therefore, you can use it wherever and whenever you like, based on your situation.

What is it for? trim spaces at the beginning and end of the line? If you specify a password on the site when registering and somehow accidentally press the space bar and do not notice it, then your password will consist, for example, not of four characters, but of five, including your space. And you will not understand why the password is not suitable, because the hash of this string will be different. Therefore, I always recommend trimming spaces in a line to avoid such nuances. Now we will move on to consider an example in practice.

$string_pass = " 1234 " ;
$password = md5(trim($string_pass ));
$password2 = md5($string_pass );
echo $password;
echo "
"
;
echo $password2;
?>

We create a variable that will be our password, and specifically indicate a space at the beginning and at the end of the line. Next, we create a variable in which the hashed password will already be stored, and pass the line through trim function, which will first remove all unnecessary spaces, and only then we will get the hashed password. And in the second variable we do not use the function to remove spaces and immediately hash the string. We then display the two results on the browser screen and see that they are completely different, even though we used the same string both times. However, due to the spaces, the result is completely different, so you need to be extremely careful with this matter. And one last thing I should tell you. There are two more functions that remove spaces at the beginning of a line, or at the end of a line, and they are called ltrim And rtrim respectively. Therefore, if you need to remove spaces from any of the sides, use them. And with this I conclude this article and wish you success in all your work.

In any language, when working with strings, a typical task is to remove spaces both at the beginning and at the end of the line. In PHP there are three functions for these purposes: ltrim(), rtrim(), trim(). The ltrim() function removes spaces at the beginning of a line, rtrim() - at the end of a line, trim() - at both the beginning and the end. What's interesting is that these functions, in addition to spaces, also remove the newline, carriage return, tab, and null character escape sequences.

$example = "\tHi everybody\n"; var_dump(trim($example)); var_dump(rtrim($example)); var_dump(ltrim($example));

As a result we get:

String "Hi everybody" (length=12) string " Hi everybody" (length=14) string "Hi everybody " (length=13)

What's most interesting is that the above functions can also remove user-specified characters. To do this, the above functions need to pass as the second argument a string containing the characters to be deleted. For example:

$example = "YHi everybody\n"; var_dump(trim($example, " y")); var_dump(rtrim($example, " y\n")); var_dump(ltrim($example, " yH"));

As a result:

String "Hi everybody " (length=13) string " yHi everybod" (length=13) string "i everybody " (length=12)