Your own trim, rtrim and ltrim functions in PHP

Web-hosting business can now be started for just $19.95 with unlimited resources. Start your own.

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.

  1. function my_trim( $string = '' , $chrs = " \t\r\n\0\x0B" ) {
  2.    
  3.     //Make the removable characters array index, for faster look-up later
  4.     $chrs    = array_flip( str_split( $chrs ) );
  5.     $count   = 0;
  6.    
  7.     while( isset( $string[0] ) && isset( $chrs[ $string[0] ] ) ) {
  8.         $string = substr( $string , 1 );
  9.     }
  10.    
  11.     $length  = strlen( $string );
  12.    
  13.     while( $length && isset( $chrs[ $string[ $length - 1 ] ] ) ) {
  14.         $string = substr( $string , 0 , -1 );
  15.         --$length;
  16.     }
  17.    
  18.     return $string;
  19. }
PHP Code

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.
  1. function my_ltrim( $string = '' , $chrs = " \t\r\n\0\x0B" ) {
  2.      //Make the removable characters array index, for faster look-up later
  3.     $chrs   = array_flip( str_split( $chrs ) );
  4.     $count = 0;
  5.    
  6.     while( isset( $string[0] ) && isset( $chrs[ $string[0] ] ) ) {
  7.         $string = substr( $string , 1 );
  8.     }
  9.    
  10.     return $string;
  11. }
PHP Code

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.
  1. function my_rtrim( $string = '' , $chrs = " \t\r\n\0\x0B" ) {
  2.      //Make the removable characters array index, for faster look-up later
  3.     $chrs   = array_flip( str_split( $chrs ) );
  4.     $length = strlen( $string );
  5.    
  6.     while( $length && isset( $chrs[ $string[ $length - 1 ] ] ) ) {
  7.         $string = substr( $string , 0 , -1 );
  8.         --$length;
  9.     }
  10.    
  11.     return $string;
  12. }
PHP Code

Testing with your input,
  1. echo my_trim( ' Hello World! ' );
  2. echo my_ltrim( ' Hello World! ' );
  3. echo my_rtrim( ' Hello World! ' );
PHP Code



  1. High Performance Hosting is now $3.96 a month


© 2012-2017 PageConfig.com - Scripts - Twitter