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.  

Leave a Reply

Your email address will not be published. Required fields are marked *

*