Home >Backend Development >PHP Problem >How to solve invalid and extra newlines in PHP strings
Invalid newline character:
Example:
<?php echo 'hello\n'; echo 'world'; ?>
The above problem Mainly because in PHP single quotes
and double quotes
can be expressed, but double quotes also have a special function: the content in the double quote string can be interpreted and replaced. This is What single quotes don’t have.
After modification:
<?php echo "hello\n"; echo 'world'; ?>
Excess newlines:
//php 不同系统的换行 //不同系统之间换行的实现是不一样的 //linux 与unix中用 /n //MAC 用 /r //window 为了体现与linux不同 则是 /r/n //所以在不同平台上 实现方法就不一样 //php 有三种方法来解决
1. Use str_replace to replace newlines
$str = str_replace(array("/r/n", "/r", "/n"), "", $str);
2. Use regular replacement
$str = preg_replace('//s*/', '', $str);
3. Use variables defined by php
$str = str_replace(PHP_EOL, '', $str);
Recommended: "2021 PHP interview questions summary (collection)" "php video tutorial"
The above is the detailed content of How to solve invalid and extra newlines in PHP strings. For more information, please follow other related articles on the PHP Chinese website!