Home  >  Article  >  Backend Development  >  How to solve invalid and extra newlines in PHP strings

How to solve invalid and extra newlines in PHP strings

autoload
autoloadOriginal
2021-04-01 11:26:332088browse

How to solve invalid and extra newlines in PHP strings

Invalid newline character:

Example:

<?php 
    echo &#39;hello\n&#39;; 
    echo &#39;world&#39;; 
?>

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 &#39;world&#39;; 
?>

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(&#39;//s*/&#39;, &#39;&#39;, $str);

3. Use variables defined by php

      
 $str = str_replace(PHP_EOL, &#39;&#39;, $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!

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