Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does ltrim remove one character too much?

Tags:

php

trim

<?php
echo ltrim('12Hello World', '\x30..\x39');
echo "<br />";
echo ltrim('12Hello World', '0123456789');

Gives the output:

ello World
Hello World

Why? I understand that it is an array of characters and every character is stripped but if that's the case why is the H removed in the first case?

like image 982
Ms01 Avatar asked Jun 16 '14 07:06

Ms01


2 Answers

'\x30..\x39' is the following character mask:

  • \
  • x
  • 3
  • 0..\, i.e. anything from 0 through \, which includes H
  • 9

You need to use double quotes, otherwise the \xXX escape sequences aren't interpreted as bytes:

"\x30..\x39"

That's the character mask for anything from byte x30 through x39, which is 0 - 9 in ASCII and compatible encodings.

like image 161
deceze Avatar answered Oct 13 '22 00:10

deceze


Escape sequences aren't interpreted inside single quotes. So your second argument is interpreted literally. It says to trim the following characters:

  • \
  • x
  • 3
  • 0 through \
  • x
  • 3
  • 9

If you take a look at an ASCII chart, you'll see that the range 0 through \ includes all the uppercase letters.

Change to a double-quoted string to have the hex escape sequence interpreted:

echo ltrim("12Hello World", "\x30..\x39")

produces:

Hello World
like image 39
Barmar Avatar answered Oct 12 '22 23:10

Barmar