PHP - String String Functions

Introduction

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

Demo

<?php
     $text = '   this is a test '; 

     echo strlen($text); //ww  w  . jav a2 s  .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')); 
?>

Result

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