Home > Backend Development > PHP Tutorial > A pitfall of the rtrim function

A pitfall of the rtrim function

WBOY
Release: 2016-07-28 08:25:48
Original
1192 people have browsed it

Briefly describe the problems encountered today:
There is the following code snippet in my code:

<code><span><span><?php</span>
    header(<span>"Content-type:text/html;charset=utf8"</span>);
    <span>echo</span> rtrim(<span>"威、"</span>,<span>"、"</span>);</span></code>
Copy after login

The original expectation was to output "power". However, it backfired and several garbled codes were output. Why is this? Let me explain in detail.
First of all, you need to know the function of the rtrim function. Its second parameter is a string, and each char in it will be taken out as the character to be removed. For example:

<code><span><span><?php</span><span>echo</span> rtrim(<span>"blakefezabc"</span>, <span>"cab"</span>);
    <span>//output blakefez</span></span></code>
Copy after login

Yes, the output is blakefez.
The implementation of this function should be relatively simple:
①. Traverse leftward starting from the last character of the first parameter to determine whether the byte is in the second parameter.
②. If it exists, remove the byte and continue with the first step. If not, end.
Please note that I used bytes above. Yes, this function is non-multibyte-safe. In other words, when some characters in our parameters are multi-byte, undesired results will occur. For example, rtrim ("power,", ",") mentioned at the beginning. Because "Wei" and "," are all utf8 encoded. That is, multi-byte characters. Among them, the encoding of "威" is 0xE5 0xA8 0x81, and the encoding of "," is 0xE3 0x80 0x81. Therefore, in the eyes of the rtrim function, what it sees is: rtrim("0xE5 0xA8 0x81 0xE3 0x80 0x81", "0xE3 0x80 0x81"); so the final output result is 0xE5 0xA8. At this time, when converted to utf8 encoding, it becomes garbled.

').addClass('pre-numbering').hide(); $(this).addClass('has-numbering').parent().append($numbering); for (i = 1; i ').text(i)); }; $numbering.fadeIn(1700); }); });

The above has introduced a pitfall of the rtrim function, including aspects of it. I hope it will be helpful to friends who are interested in PHP tutorials.

Related labels:
source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template