Skip to content

Strings

These functions are for working with strings.

stringSpacer

This function converts the input such that after the first character, every capital letter or number becomes a space plus that character.

<?php

function stringSpacer($text){     //--------------------------------------------------------------------
// Given a text string, after the first character, every capital letter or
// number becomes a space plus that character --> "FirstName" becomes "First Name",
// and "HomeStreet2" becomes "Home Street 2"
// Unless the character preceeding is itself a capital or number

  for ($i = 0; $i < strlen($text); $i++){
    $ordNum = ord(substr($text,$i,1));
    if ((($ordNum <= 57 AND $ordNum >= 48) OR ($ordNum <= 90 AND $ordNum >= 65)) AND $previous == false) {
      $output .= " " . substr($text,$i,1);
      $previous = true;
    }
    else {
      $output .= substr($text,$i,1);
      $previous = false;
    }  
  }
  $output = trim($output);
  return $output;

} // end stringSpacer

?>

getTitleCase

This function converts the input to Title Case and returns the result.

<?php

function getTitleCase( $strText ) { //--------------------------------------------------------------------
  // Converts $title to Title Case, and returns the result.
  // Based on a script found on https://www.sitepoint.com/title-case-in-php/

  // Our array of 'small words' which shouldn't be capitalised if they aren't the first word. Add your own words to taste.
  $arrSmallWords = array( 'a', 'an', 'and', 'at', 'but', 'by', 'else', 'for', 'from', 'if', 'in', 'into', 'is', 'nor', 'of', 'off', 'on', 'or', 'out', 'over', 'the', 'then', 'to', 'when', 'with' );

  // Our array of acronyms and 'funky' words which need special treatment. Add your own words to taste.
  $arrFunkyWords = array( 'PHP', 'JavaScript' );

  // Start by forcing the string to lowercase
  $strText = strtolower( $strText );

  // Split the string into separate words
  $arrWords = explode( ' ', $strText );

  // Loop through the array
  foreach ( $arrWords as $key => $strWord ) {
    // If this word is one of the 'funky' words, use that 'funky' word. If this word is the first, last, or it's not one of the custom words, capitalise it with ucfirst().
    if ( in_array( strtoupper( $strWord ), array_map( 'strtoupper', $arrFunkyWords ), true ) ) {
      $arrWords[ $key ] = $arrFunkyWords[ array_search( strtoupper( $strWord ), array_map( 'strtoupper', $arrFunkyWords ), true ) ];
    } elseif ( $key == 0 OR $key == ( count( $arrWords ) - 1 ) OR !in_array( $strWord, $arrSmallWords, true ) ) {
      $arrWords[ $key ] = ucfirst( $strWord );
    }
  }

  // Join the words back into a string
  $strTitle = implode( ' ', $arrWords );

  // Return the result
  return $strTitle;

} //end function getTitleCase

?>