Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why is PHP Treating Carriage Return / Linefeed Combo as a Single Byte?

Tags:

php

I have a php script that truncates a string at 41 bytes. I call strlen on the string to check its size. However, if the string has a "\r\n" combo, this combo is treated as one byte. So in my case instead of 42 bytes, PHP thinks it is 41 bytes.

Also substr truncates it to 42 instead of 41 bytes.

  if (strlen($value) > 41)
  {
   $value = substr($value, 0, 41);

Another weird condition. I have a large set of data I am passing through this function. Thousands of strings. If I use a simpler test data set then the code works correctly, treating "\r\n" as 2 bytes.

Any ideas? Thanks.

like image 724
jriggs Avatar asked Jan 05 '11 16:01

jriggs


People also ask

What is carriage return line feed combination?

CR = Carriage Return ( \r , 0x0D in hexadecimal, 13 in decimal) — moves the cursor to the beginning of the line without advancing to the next line. LF = Line Feed ( \n , 0x0A in hexadecimal, 10 in decimal) — moves the cursor down to the next line without returning to the beginning of the line.

What is carriage return in PHP?

If you need to insert a Carriage Return in a string in PHP: Carriage return is: "\r" But carriage return (CR) is different from "new line" (NL) New Line (NL) is "\n" What in HTML is called "line break" is the sum of a CR and a NL.

Is \a carriage return or line feed?

A line feed means moving one line forward. The code is \n . A carriage return means moving the cursor to the beginning of the line. The code is \r .

What is a linefeed character?

(computing) The character (0x0a in ASCII) which advances the paper by one line in a teletype or printer, or moves the cursor to the next line on a display.


1 Answers

convert the combo \r\n to \n , do whatever u need , then revert all \n's to the combo ...

str_replace("\r\n","\n",$value);
if (strlen($value) > 41)
  {
   $value = substr($value, 0, 41);
str_replace("\n","\r\n",$value);

hope this will work for you not knowing what are you trying to do

like image 68
Rami Dabain Avatar answered Oct 16 '22 11:10

Rami Dabain