Comparing and Transforming Strings

String functionality and manipulation methods are an enormous part of the PHP language and should be studied heavily. The following functions are by no means an exhaustive list of what can be done with strings and the resources on the php site should be read over.

When comparing strings, it’s best to use strcmp() and strcasecmp() which is a case insensitive version of the former. Both of these functions will return a zero value to indicate that the strings are equal, less than zero if the first string is less than the second, and greater than zero if the first string is greater.

  1.  
  2. int strcmp ( string $str1 , string $str2 )
  3.  
  4. int strcasecmp ( string $str1 , string $str2 )
  5.  

Also worth noting is the strncmp() function that works similar with one difference. It will only do a comparison on the first n characters.

  1.  
  2. int strncmp ( string $str1 , string $str2 , int $n )
  3.  

The strtr() function is used to translate characters or replace substrings. I can be given either two or three parameters, depending if you want to replace one or more values.

  1.  
  2. string strtr ( string $str , string $from , string $to )
  3. string strtr ( string $str , array $replace_pairs )
  4.  
  5. echo strstr (’abc’, ’a’, ’I’); //Ibc
  6.  
  7. $subst = array (
  8.         ’1’ => ’I’,
  9.         ’2’ => ’S’,
  10. );
  11.  
  12. echo strtr (123’, $subst); //IS3
  13.  

Heredoc Syntax

Heredoc is a strange but necessary way to create a complex string. The functionality provided is almost identical to double quoted strings except there are no quotes.

The heredoc syntax uses the special operator ‘<<<' followed by a user defined identifier. The same identifier on a new line must be used to close the string followed by an optional semicolon. This identifier is restricted by the same rules as a regular variable name.

  1.  
  2. $what = "Certification";
  3. echo <<<TEXT
  4. Zend PHP "$what"
  5. TEXT;
  6.  

This will output ‘Zend PHP “Certification”‘.
Heredoc syntax can not be used for initializing class properties. Since PHP 5.3, this limitation is valid only for heredocs containing variables.