PHP - String String Functions


PHP has a whole set of predefined functions that help you in interacting with strings.


     $text = '   this is a test '; 

     echo strlen($text); //from  w w  w .  jav a2s.c  o m
     $text = trim($text); 
     echo $text; 
     echo strtoupper($text); 
     echo strtolower($text); 
     $text = str_replace('is', 'are', $text); 
     echo $text; 
     echo substr($text, 2, 6); 
     var_dump(strpos($text, 'can')); 
     var_dump(strpos($text, 'could')); 


Here, we are playing with a string with different functions:

Function Description
strlenreturns the number of characters that the string contains.
trim returns the string, removing all the blank spaces to the left and to the right.
strtoupper and strtolower return the string with all the characters in upper or lower case respectively.
str_replace replaces all occurrences of a given string by the replacement string.
substr extracts the string contained between the positions specified by parameters, with the first character being at position 0.
strposshows the position of the first occurrence of the given string. It returns false if the string cannot be found.

Related Topics