Home  >  Article  >  Backend Development  >  How to remove spaces and newlines from strings in php

How to remove spaces and newlines from strings in php

王林
王林Original
2020-10-12 12:00:484739browse

php method to remove spaces and newlines in strings: This can be achieved through regular expressions, such as [preg_replace('//s*/', '', $str);]. It can also be implemented through the PHP_EOL variable, such as [str_replace(PHP_EOL, '', $str);].

How to remove spaces and newlines from strings in php

The specific method is as follows:

(Recommended tutorial: php video tutorial)

1. Use str_replace to replace

$str = str_replace(array("\r\n", "\r", "\n"), "", $str);

2. Use regular replacement

$str = preg_replace('//s*/', '', $str);

3. Use variables defined by php (recommended)

$str = str_replace(PHP_EOL, '', $str);

Of course we can define him as a function and then replace them together so that this code snippet can be reused.

function trimall($str){
    $qian=array(" "," ","\t","\n","\r");
    return str_replace($qian, '', $str);   
}

Related recommendations: php training

The above is the detailed content of How to remove spaces and newlines from strings in php. For more information, please follow other related articles on the PHP Chinese website!

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