Home  >  Article  >  Backend Development  >  Using regular expressions to clear whitespace in strings in PHP_PHP Tutorial

Using regular expressions to clear whitespace in strings in PHP_PHP Tutorial

WBOY
WBOYOriginal
2016-07-21 15:32:211057browse

If you want to remove whitespace at the beginning and end of a string you can use the PHP internal function trim(). However, we often want to clear the white space completely. You need to clear the starting and ending blanks, turn multiple blanks into one blank, and use a rule to handle other blanks of the same type.

This can be done using PHP regular expressions

The following example can remove extra Whitespace

Copy code Code As follows:

$str = " This line containstliberal rn use of whitespace.nn";

// First remove the leading/trailing whitespace
//Remove the starting and ending whitespace
$str = trim($str);

// Now remove any doubled-up whitespace
//Remove the whitespace that is crowded with others
$str = preg_replace('/s(?=s)/', '', $str);

// Finally, replace any non-space whitespace, with a space
/ /Finally, remove the non-space whitespace and replace it with a space
$str = preg_replace('/[nrt]/', ' ', $str);

// Echo out: 'This line contains liberal use of whitespace.'
echo "
{$str}
";
?>


The above example is step by step Remove all whitespace. First we use the trim() function to remove the starting and ending whitespace. Then, we use preg_replace() to remove duplicates. s represents any whitespace. (?=) means look forward. It means that it only matches characters that are followed by the same character as itself. So this regex means: "Any whitespace character followed by a whitespace character." We replace it with whitespace, which removes it and leaves only the whitespace character.

Finally, we use another regular expression [nrt] to find any remaining newlines (n), carriage returns (r), or tabs (t). We replace these with a space.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/322830.htmlTechArticleIf you want to remove the blanks at the beginning and end of the string, you can use the PHP internal function trim(). However, we often want to clear the white space completely. You need to clear the starting and ending blanks and change...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn