While we already have trim()
, ltrim()
and rtrim()
in php, here is how we can implement the same feature. These are listed here just for understanding the process. In practice, you are recommended to use the built-in functions for performance and consistency reasons.
my_trim()
will remove specified characters from both ends of your string, and in case no such characters are specified as second argument to the function, will remove white-space from both ends of the provided string.
function my_trim( $string = '' , $chrs = " \t\r\n\0\x0B" ) { //Make the removable characters array index, for faster look-up later $chrs = array_flip( str_split( $chrs ) ); $count = 0; while( isset( $string[0] ) && isset( $chrs[ $string[0] ] ) ) { $string = substr( $string , 1 ); } $length = strlen( $string ); while( $length && isset( $chrs[ $string[ $length - 1 ] ] ) ) { $string = substr( $string , 0 , -1 ); --$length; } return $string; }
my_ltrim()
will remove specified characters from start of your string, and in case no such characters are specified, will remove just white-space from start.
function my_ltrim( $string = '' , $chrs = " \t\r\n\0\x0B" ) { //Make the removable characters array index, for faster look-up later $chrs = array_flip( str_split( $chrs ) ); $count = 0; while( isset( $string[0] ) && isset( $chrs[ $string[0] ] ) ) { $string = substr( $string , 1 ); } return $string; }
my_rtrim()
will remove specified characters from end of your string, and in case no such characters are specified, will remove just white-space from the end.
function my_rtrim( $string = '' , $chrs = " \t\r\n\0\x0B" ) { //Make the removable characters array index, for faster look-up later $chrs = array_flip( str_split( $chrs ) ); $length = strlen( $string ); while( $length && isset( $chrs[ $string[ $length - 1 ] ] ) ) { $string = substr( $string , 0 , -1 ); --$length; } return $string; }
Testing with your input:
echo my_trim( ' Hello World! ' ); echo my_ltrim( ' Hello World! ' ); echo my_rtrim( ' Hello World! ' );