PHP clear string blank method

 Although PHP's trim function can clear the whitespace before and after the string , in some cases, not only the whitespace before and after the string needs to be cleared, but also all the whitespace between the strings must be cleared . Use the PHP regular expression technique to deal with, the main program operation is actually only two parts, please see the following example.


Example, first clear the blank characters before and after the string and then remove the blanks between the strings
<?php
$TestStr = "This string have many whitespace.";
echo'<pre>'.$TestStr.'<br></pre>';

$TestStr = trim($TestStr);

echo'<pre>' .$TestStr.'<br></pre>';

$TestStr = preg_replace('/\s(?=)/','', $TestStr);
echo'<pre>'.$TestStr.'</ pre>';
?>
Output result
 This string have many whitespace. 
This string have many whitespace.
Thisstringhavemanywhitespace.
At the beginning of the example, a $TestString is prepared, which is a string with blanks before and after and between the strings. The two red marks in the example are the key to remove the string blanks. The first key is to use the built-in trim of PHP Function, he can easily remove the blanks before and after the original string. From the first line and the second line of the output result, you can see that the blanks before and after have been removed. Then the second red mark is used. PHP regular expression skills, where "\s" represents all whitespace characters, including spaces, tabs, form feeds... etc., and "(?=)" represents forward query, the whole paragraph means to find All the blank characters are replaced with "", which means that all the blank characters disappear, so the output of the third line of the example becomes all the English letters connected together, because the blanks between the letters have been cleared.

Post a Comment

0 Comments