_split_str_by_whitespace

Breaks a string into chunks by splitting at whitespace characters.

Description

(array) _split_str_by_whitespace( (string) $string, (int) $goal ); 

The length of each returned chunk is as close to the specified length goal as possible, with the caveat that each chunk includes its trailing delimiter. Chunks longer than the goal are guaranteed to not have any inner whitespace.

Joining the returned chunks with empty delimiters reconstructs the input string losslessly.

Input string must have no null characters (or eventual transformations on output chunks must not care about null characters)

0 => 1234 67890 , // 11 characters: Perfect split 1 => 1234 , // 5 characters: 1234 67890a was too long 2 => 67890a cd , // 10 characters: 67890a cd 1234 was too long 3 => 1234 890 , // 11 characters: Perfect split 4 => 123456789 , // 10 characters: 123456789 1234567890a was too long 5 => 1234567890a , // 12 characters: Too long, but no inner whitespace on which to split 6 => 45678 , // 11 characters: Perfect split 7 => 1 3 5 7 90 , // 11 characters: End of $string

Returns (array)

Numeric array of chunks.

Parameters (2)

0. $string (string)
The string to split.
1. $goal (int)
The desired chunk length.

Usage

  1. if ( !function_exists( '_split_str_by_whitespace' ) ) { 
  2. require_once ABSPATH . WPINC . '/formatting.php'; 
  3.  
  4. // The string to split. 
  5. $string = ''; 
  6.  
  7. // The desired chunk length. 
  8. $goal = -1; 
  9.  
  10. // NOTICE! Understand what this does before running. 
  11. $result = _split_str_by_whitespace($string, $goal); 
  12.  

Defined (1)

The function is defined in the following location(s).

/wp-includes/formatting.php  
  1. function _split_str_by_whitespace( $string, $goal ) { 
  2. $chunks = array(); 
  3.  
  4. $string_nullspace = strtr( $string, "\r\n\t\v\f ", "\000\000\000\000\000\000" ); 
  5.  
  6. while ( $goal < strlen( $string_nullspace ) ) { 
  7. $pos = strrpos( substr( $string_nullspace, 0, $goal + 1 ), "\000" ); 
  8.  
  9. if ( false === $pos ) { 
  10. $pos = strpos( $string_nullspace, "\000", $goal + 1 ); 
  11. if ( false === $pos ) { 
  12. break; 
  13.  
  14. $chunks[] = substr( $string, 0, $pos + 1 ); 
  15. $string = substr( $string, $pos + 1 ); 
  16. $string_nullspace = substr( $string_nullspace, $pos + 1 ); 
  17.  
  18. if ( $string ) { 
  19. $chunks[] = $string; 
  20.  
  21. return $chunks;