santa
santa

Reputation: 12512

ltrim strips more than needed

Is there a way to limit exactly what ltrim removes in PHP.

I had a the following outcome:

$str = "axxMyString";
$newStr = ltrim($str, "ax");
// result MyString and it should have been xMyString

Upvotes: 1

Views: 829

Answers (5)

Billy Moon
Billy Moon

Reputation: 58531

I think the confusion has come in because ltrim receives a list of characters to remove, not a string. Your code removes all occurrences of a or x not the string ax. So axxxaxxaMyString becomes MyString and axxaiaxxaMyString becomes iaxxaMyString.

If you know how many characters you need to remove, you can use substr() otherwise for more complicated patterns, you can use regular expressions via preg_replace().

Upvotes: 0

Francesco Terenzani
Francesco Terenzani

Reputation: 1391

You could use a regexp too:

$string = preg_replace('#^ax#', '', $string);

Upvotes: 0

Wh1T3h4Ck5
Wh1T3h4Ck5

Reputation: 8509

ltrim() manual:

Strip whitespace (or other characters) from the beginning of a string.

So...

$newStr = ltrim($str, "ax");

This will remove every character 'a' and 'x' at the beginning of string $str.

Use substr() to get part of string you need.

Upvotes: 1

halfdan
halfdan

Reputation: 34214

The second parameter species each character that will be trimmed. Because you defined both a and x the first the letters got removed from your string.

Just do:

$newStr = ltrim($str, "a");

and you should be fine.

Upvotes: 0

Lekensteyn
Lekensteyn

Reputation: 66415

If you know that the first two characters should be stripped, use:

$str = substr($str, 2);

ltrim($str, $chars) removes every occurence from $chars from the left side of the string.

If you only want to strip the first two characters when these equals ax, you would use:

if (substr($str, 0, 2) == 'ax') $str = substr($str, 2);

Upvotes: 4

Related Questions