There are many string functions that can be used for different needs by programmers. A few most commonly used PHP string functions are discussed in this tutorial.

Chr

The function is used to convert a numeric value into corresponding character.

Syntax

chr ( int $num)

This function accepts an unsigned integer between 0 and 255 and returns the corresponding single character string value.

Example

 
 
<?php
for ($i=67;$i<=80;$i++)
{             
                echo chr($i);
                echo "<br>";
}             
?>

Output

PHP string function chr

explode

This function accepts a delimiter and a string. It returns an array of words that make this string separated at delimiters. The delimiter is not included in the set of words returned.

syntax

explode ( string $delimiter , string $string [, int $limit = PHP_INT_MAX ] )

The first argument is the character you wish to use for splitting the string. The second argument is the string to be split. The last argument is optional. It represents the max number of string you want to have in the output array. The last element of the output array will contain all the remaining characters after the limit.

Example

 
 
<?php
$inputStr="this is my string";
$strArr= explode(" ",$inputStr);
$i=0;
while($i<count($strArr))
{
echo $strArr[$i];
echo "<br>";
$i++;
}
?>

In the above example the input string is exploded using single space as delimiter and the strings of the words in input string gets stored in strArr. Using a while loop the words are displayed one each in a line

Output

explode php string function

implode

Implode, as you can guess, does just the opposite of explode function. It takes an array of words and combines them to form a string. Join and implode PHP String Functions do the same task.

Syntax

implode ( string $joinwith , array $words )

The first argument is the character string that you wish use to combine the words. The second argument is the array that contains the words to be joined.

Example

In the example here we have stored the words in $inputarr and are using “-“ (hyphen) to join the words using implode function

 
 
  1. <?php
  2. $inputarr[0]="this";
  3. $inputarr[1]="is";
  4. $inputarr[2] ="my";
  5. $inputarr[3] ="string";
  6. $strArr= implode("-",$inputarr);
  7. echo $strArr;
  8. ?>

Output

implode php string function

lcfirst

This function is used when the first character of the given string is to be converted to lower case.

Syntax

lcfirst(string $strInput)

The lcfirst function accepts single string as an argument and returns a string with lowercased first character. The argument can be a string or a variable storing a string value.

Example

 
 
<?php
$str="CSVEDA";
echo lcfirst($str);
?>

Output

lcfirst php string function

strlen()

This function is needed to count the number of bytes of the input string. It doesn’t count characters but bytes. It means if you have blank or white spaces within the input string, before or after characters, they will be counted as part of string.

Syntax

strlen(string $strInput)

This function accepts one string argument and returns integer value as the count of characters of the string including white spaces.

Example

 
 
<?php
$InputStr="Ba Ba Black Sheep Have You any Wool";// no spaces in beginning and end
echo strlen($InputStr)."<br>";
$InputStr="  Ba Ba Black Sheep Have You any Wool  ";// two spaces added at beginning and end
echo strlen($InputStr)."<br>";
$InputStr="  Ba   Ba   Black   Sheep   Have   You   any   Wool  ";// spaces added at beginning and end and in between words
echo strlen($InputStr)."<br>";
?>

Output

strlen php string function

ltrim, rtrim,trim

If you are working with text data from different sources, then sometimes the text data contains whitespaces at wrong places. It can be at beginning or end of the text. These additional spaces may give unexpected results while manipulating text data.  For such cases PHP provides three functions rtrim, ltrim and trim. These PHP String Functions allow you to remove blank spaces or unwanted characters at end, start or both ends of the string respectively.

Syntax

ltrim(string $strInput [,string $strMask]) – remove whitespace or characters specified by $strMask at the start of first string argument.

rtrim(string $strInput [,string $strMask])- remove whitespace or characters specified by $strMask at the end of first string argument.

trim(string $strInput [,string $strMask])- remove whitespace or characters specified by $strMask at both end of the first string argument.

$strinput is the string from which the whitespaces of characters have to be removed and $strMask is the string specifying the characters to be removed

Example

 
 
<?php
$str="    CSVEDA     ";
echo strlen($str)."<br>";// display total count of characters in $str
echo strlen(ltrim($str))."<br>";// display total count of characters in $str after trimming white space in beginning
echo strlen(rtrim($str))."<br>";// display total count of characters in $str after trimming white space at end
echo strlen(trim($str))."<br>";// display total count of characters in $str after trimming white space at both ends
$str="*****CSVEDA//////";
echo ltrim($str,"*")."<br>";// display $str after trimming * from left
echo rtrim($str,"/")."<br>";// display $str after trimming / from right
echo trim($str,"*")."<br>";// display $str after trimming *
echo trim($str,"/")."<br>";// display $str after trimming /
?>

Output

 trim php string functions

parse_str

If you are using a query string to pass on variables among different web pages, then parse_str is a useful function. This function parses an input string, extracts variables and assigns values to them.

Syntax

parse_str ( string $queryString [, string $resArray ] )

This function takes an encoded string $queryString as first argument. It contains pairs of variable value pairs separated by &. The second argument name of the array to store the parsed values is optional.

Example

Without array argument for result of parsing

 
 
<?php
$Querystr="name=James&Deptt=Sales&Salary=8000";
parse_str($Querystr);
echo $name."<br>";
echo $Deptt."<br>";
echo $Salary."<br>";
?>

Output

parse_str php string function

 

With array argument for result of parsing

 
 
<?php
$Querystr="name=James&Deptt=Sales&Salary=5000";
parse_str($Querystr, $vals);
echo $vals["name"]."<br>";
echo $vals["Deptt"]."<br>";
echo $vals["Salary"]."<br>";
?>

Output

 

parse string php function

str_replace(), str_ireplace()

There are many times when you may want to replace certain characters in a string or file with some other characters in one go. str_replace() and  str_ireplace() are two such PHP String Functions that help you in replacing characters without or with case sensitivity respectively.

Syntax

str_replace ( string $strSearch , string $strReplace , string $strSource[,int $chrCount ] )

str_ireplace ( string $strSearch , string $strReplace , string $strSource[,int $chrCount ] )

In both these functions the strSearch is searched in strSource and replaced with strReplace at all places. chrCount is the integer argument that stores the count of replacements happened. str_ireplace follows the case of the characters while making replacements. Both functions return the final string with replacements.

Example

 
 
<?php
$InputStr="Ba Ba Black Sheep Have You any Wool";
echo str_replace("ba","Ga",$InputStr, $chrRep)."<br>";// No replacement since case of search string does not match with similar characters in Input String
echo "<font color=red>count of replacements=".$chrRep."</font><br>";// the fourth argument of str_replace function returns the count of replacements done
echo str_replace("Ba","Ma",$InputStr,$chrRep)."<br>";// 'Ba' replaced by 'Ma' since case of search string matches with similar characters in Input String
echo "<font color=red>count of replacements=".$chrRep."</font><br>";// the fourth argument of str_replace function returns the count of replacements done
echo str_ireplace("bA","Ha",$InputStr,$chrRep)."<br>";// Replacement successful using str_ireplace function without case consideration of search string
echo "<font color=red>count of replacements=".$chrRep."</font><br>";// the fourth argument of str_replace function returns the count of replacements done
?>

Output

str_replace php string function

str_word_count

To serve the need of counting words in a given string or placing word in a array, among PHP String Functions you have str_word_count function.

Syntax

str_word_count ( string $strInput [, int $format [, string $strList ]] )

This function has only one essential argument and two optional arguments. When only string is passed as argument, the total count of words in the string is returned.

  • If second argument is 0 the count of words is returned.
  • If second argument is 1 then the function returns an array of all words of the input string as elements accessible using index.
  • If second argument is 2 then the function returns an associative array of all words of the input string. Index position of word is taken as key of this associative array and the word as its value.

The third argument is used when you want to specify some combination of characters in the input as a word.

Example

 
 
<?php
$InputStr="Ba Ba Black Sheep Have You any Wool";
echo str_word_count($InputStr)."<br>";
$arr=str_word_count($InputStr,1);
print_r($arr);
echo "<br><br>";
$arr=str_word_count($InputStr,2);
print_r($arr);
?>

Output

str_word_count php string function

strrev()

This function is used to display the reverse of a given input string.

Syntax

strrev(string $strInput)

This function accepts one string argument and returns the string in reverse order.

Example

 
 
<?php
$InputStr="I am a little teapot";
echo strrev($InputStr);
?>

Output

strrev php string function

substr()

This function is used to display the substring extracted from  a given input string.

Syntax

substr (string $strInput, int $startPos, int $substrLen)

This function accepts a string argument, the start position from where to begin the substring and the length of substring from that position. It returns the substring based on these values.

Example

 
 
<?php
$InputStr="I am a little teapot";
echo substr($InputStr,3,6);// extracts 6 characters starting from 3rd character of input string
?>

Output

substr php string function