Here I am trying to simulate built in function "ltrim" (that strips characters from the beginning of the string) in PHP here is the code I have written
function leftTrim(string $Sstr, mixed $char) : string
{
$i = 0;
for(; $i< strlen($Sstr); $i ): // loop on the string
for($j=0; $j <strlen($char); $j ): // loop on the characters
if($Sstr[$i] === $char[$j])
{
$Sstr[$i] = " ";
break;
}
endfor;
endfor;
return $Sstr;
}
but I found two problems with this code:
it replaces each character with a space character that means that the length of the code remains the same.
this function trims characters from the middle of the string where it should only trim from the beginning.
CodePudding user response:
Don't replace the characters with spaces. Just find the index of the first non-matching character, then use
substr()
to get all the characters after that into the result.Stop looping when you find a character that isn't in
$char
.
There's no need for the inner loop, you can use strpos()
to check if a character is in $char
.
function leftTrim(string $Sstr, mixed $char) : string
{
for($i = 0; $i< strlen($Sstr); $i ): // loop on the string
if (strpos($char, $Sstr[$i]) === false) {
break;
}
endfor;
return substr($Sstr, $i);
}
CodePudding user response:
Barmar's answer is the correct one (by correcting and improving the OPs code).
One alternative would be to split the string to an array and unset the characters to be trimmed and then join the remaining characters back to a string:
function leftTrim(string $str, string $chars = ' '): string {
$splitted = str_split($str);
for ($i = 0; $i < count($splitted); $i ) {
if (str_contains($chars, $splitted[$i])) {
unset($splitted[$i]);
} else {
break;
}
}
return implode('', $splitted);
}