The reason that line breaks do not work when PHP fwrite line-Wrapping writes

Source: Internet
Author: User
Tags regular expression

We all know the line break in PHP: \ n, carriage return: \ r, when you need to change lines, it's usually a combination of "\ r \ n". But why does the newline character not work when we write a file using fwrite? Let's look at the following example:

<?php
$filename = ' file.txt ';
$word = ' Hello!\r\n Welcome to www.111cn.net ';
$fh = fopen ($filename, "a"); W writes a append write from the beginning
Echo fwrite ($fh, $word);
Fclose ($FH);
?>
A carriage return line character "\ r \ n" is added to the $word string, but the output is not expected, and the carriage return line character "\ r \ n" is not resolved to be a newline character, but is directly treated as a char output.

Why is this happening? After study, the original is a single double quotation mark! We put the single quotation mark "'" of the $word definition string into double quotes "". The correct wording is as follows:

$filename = ' file.txt ';
$word = "Hello!\r\n Welcome to Www.111cn.net";
$fh = fopen ($filename, "a"); W writes a append write from the beginning
Echo fwrite ($fh, $word);
Fclose ($FH);

In the above example, Echo fwrite () shows a number that represents the length of the string.

Knowledge expansion

Using double quotes (") to define a string, PHP knows more about the escape sequence for special characters:

Transfer sequence Description

\ n Line Change

\ r Carriage Return

\ t Horizontal tab

\[/td> Backslash

\$ dollar Sign

\ "Double Quotes

\[0-7]{1,3} This regular expression sequence matches a character represented by a octal symbol

\x[0-9a-fa-f]{1,2} This regular expression sequence matches a character represented in hexadecimal notation

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.