3

I was trying to achieve stripping off some beginning part from a string using php ltrim function. It works fine until it get a i character after colon : . if it find i after colon it simply ignore the i character. I know it can be done with substr or any other way but I want to know why its happening with trim. For example.

ltrim('mailto:bob@example.com','mailto:');

the above function will return bob@example.com

but if I put i after colon.. for example

ltrim('mailto:info@example.com','mailto:');

this one will return nfo@example.com

Can anybody explain what is happening?

Charles Sprayberry
  • 7,741
  • 3
  • 41
  • 50
Hasanavi
  • 8,455
  • 2
  • 29
  • 35

2 Answers2

9

The second argument to ltrim is a list of characters to remove from the left side of the string.

If you did

<?php
    ltrim('lllliiiiaaaaaatttttt', 'mailto:');
?>

You would get an empty string as the return value.

Try this instead:

<?php
    $email = 'mailto:bob@example.com';
    $fixedEmail = substr($email, 0, 7) == 'mailto:' ? substr($email, 7) : $email;
?>
fusion3k
  • 11,568
  • 4
  • 25
  • 47
Alec Gorge
  • 17,110
  • 10
  • 59
  • 71
0

ltrim() works differently that it trims all the given characters from the left until a non-matching character is found. Therefore when you put an "i" after colon in the email address, the first unmatched character is "n" and so it trims everything before it.

If your intent is to remove "mailto:", you may simply try:

str_replace('mailto:', '', 'mailto:info@example.com');
Abhay
  • 6,545
  • 2
  • 22
  • 17
  • 2
    This is not always a good idea.. for example... if I want to remove Dr, from `Dr manDrake Dracula`, it will return `manake acula` if I do `str_replace('Dr', '', 'Dr manDrake Dracula');` – Gogol Mar 07 '16 at 09:32