ltrim strips more than needed

前端 未结 5 1120
春和景丽
春和景丽 2021-01-25 01:36

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

I had a the following outcome:

$str = \"axxMyString\";
$newStr = ltrim($str, \"ax\");
// resu         


        
相关标签:
5条回答
  • 2021-01-25 02:14

    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.

    0 讨论(0)
  • 2021-01-25 02:20

    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().

    0 讨论(0)
  • 2021-01-25 02:25

    You could use a regexp too:

    $string = preg_replace('#^ax#', '', $string);
    
    0 讨论(0)
  • 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);
    
    • Manual page on ltrim()
    • Manual page on substr()
    0 讨论(0)
  • 2021-01-25 02:30

    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.

    0 讨论(0)
提交回复
热议问题