PHP String Functions


Today we will be seeing some important string functions in this PHP String Functions Tutorial.

  • String is a sequence of characters enclosed in single quotes or double quotes. For example “My name is XYZ.” is a string.
  • Various operations can be done on strings such as finding a substring in a string, calculating length of a string, encrypting a string, decrypting a string etc.
  • Some string operations are daily required and some needs a lot of code to achieve the desired output. For example finding length of a string can be used in almost any string manipulation and tasks like encrypting a string, decrypting a string requires a lot of code.
  • Functions for such tasks are inbuilt in PHP. We just have to call these functions in our program.
  • We know, built –in functions are the functions already written for the language and which can be directly used by calling them in our programs.
  • So let us see some of the inbuilt functions used for string manipulation.
  • To get demonstration of the functions given below, create a new folder named string in the htdocs folder in xampp folder. Now open a new notepad++ document and save it as index.php in the newly created string folder.
  • Write the code for every example given below in index.php file and see its output by opening the browser and typing localhost/string in the address bar.
  • Some of the string functions:
    1. echo():
      • The echo() function is used to display one or more strings.
      • You can use it to display any string or variables.
      • The string in this function can be enclosed in single quotes or double quotes.
      • The parentheses are optional. i.e. it doesn’t matter even if you don’t specify the parameters.
      • Syntax of echo() function is:
      • echo(“some text”);


        echo(‘some text’);
    2. strlen():
      • The strlen() function is used to find out the length of the given string.
      • It counts every character in a string, even a blank space.
      • Syntax of strlen() function is given below:
      • strlen(string);
      • Example of echo() and strlen():
      • Write the following code to demonstrate echo() and strlen() in the index.php file:

        <title>PHP String Functions</title>
        <h6>demonstration of:</h6>
        	//demonstration of echo()
        	echo "<strong>1) echo()</strong><br>";
        	echo("This is echo function<br>");
        	echo "Good Morning!<br>";
        	echo 'Have a nice day!<br><br>';
        	//demonstration of strlen()
        	echo "<strong>2) strlen()</strong><br>";
        	$str="Fly high, the sky is your limit.";
        	echo "<strong>Length of the string is = $len</strong>";
        • In the above code we have called the echo statement with parenthesis as well as without parenthesis.
        • Next the strlen() function counts all characters in the string given and returns its length as 32.
        • The output is shown below:
        • echo_strlen_func_output
          fig 1

    3. strpos():
      • The strpos() function is used to search for the position of another string in a given string.
      • If found the match it returns the position of the starting letter of the string that is to be searched in the given string otherwise it returns false.
      • Syntax of strpos() function is:
      • strpos(given string, string to be searched);
      • The characters are always counted from 0 onwards i.e. the first character position in the string is 0.
    4. substr():
      • The substr() function is used to extract only the required part from an existing string.
      • Syntax of substr() function is:
      • substr(string, start, length);
      • It takes 3 parameters, an existing string, the starting position from where to start extracting the string and the length up to where to extract the string.
      • The parameter length can be optional.
      • Example of strpos() and substr():
      • Write the following code to demonstrate strpos() and substr() in the index.php file:

        <title>PHP String Functions</title>
        <h6>demonstration of:</h6>
        	//demonstration of strpos()
        	echo "<strong>3) strpos()</strong><br>";
        	$str1="There is no shortcut to success.";
        	echo "Starting position of 'success' = ".strpos($str1,"success")."<br><br>";
        	//demonstration of substr()
        	echo "<strong>4) substr()</strong><br>";
        	$str2="God bless you!";
        	echo "substring from position 0 upto length 9 = <strong>".substr($str2,0,9)."</strong><br>";
        	echo "substring from position 4 = <strong>".$ans."</strong>";
        • Here, we have used strpos() function to find out the position of the word success in the given string.
        • The control starts counting the positions from 0 and not from 1.
        • Next the substr() function is used to extract the string from position 0 up to length 9 from the given string God bless you!. It returns God bless.
        • If you don’t provide length in the substr() function it will return the remaining string from the given position, as done in the statement

          . This will return the string bless you!, which starts from position 4 in the original string.

        • The output is given below:
        • strpos_substr_func_output
          fig 2

    5. strtolower():
      • The strtolower() function converts the uppercase letters in a given string to lowercase.
      • It’s syntax is given below:
      • strtolower(string);
    6. strtoupper():
      • The strtoupper() function converts the lowercase letters in a given string to uppercase.
      • It’s syntax is given below:
      • strtoupper(string);
      • Example of strtolower() and strtoupper():
      • Write the following code to demonstrate strtolower() and strtoupper() in the index.php file:

        <title>PHP String Functions</title>
        <h6>demonstration of:</h6>
        	//demonstration of strtolower()
        	echo "<strong>5) strtolower()</strong><br>";
        	$s="be HAPPY!";
        	echo "lowercase of 'be HAPPY!' = <strong>".strtolower($s)."</strong><br><br>";
        	//demonstration of strtoupper()
        	echo "<strong>6) strtoupper()</strong><br>";
        	$s1="welcome to PHP!";
        	echo "uppercase of 'welcome to PHP!' = <strong>".strtoupper($s1)."</strong><br><br>";
        • Here, in the above code we have demonstrated the strtolower() and strtoupper() functions.
        • Output is shown below:
        • strtolower_strtoupper_func_output
          fig 3

    7. trim();
      • The trim() function is used to erase the predefined characters and whitespaces from both the sides of a string.
      • Predefined characters are characters like \0, \n, \t etc.
      • Syntax of trim() function is:
      • trim(string,characters);
      • It takes 2 parameters a string that is to be trimmed and which characters are to be erased from the string.
      • The second parameter is optional. In the absence of second parameter the function trim() erases all the extra spaces at both sides of the string.
    8. wordwrap():
      • The wordwrap() function is used to cut the given string after it reaches to a specific length.
      • It is similar to the wordwrap operation in notepad.
      • Syntax of wordwrap() function is:
      • wordwrap(string, width, break, cut);
      • The wordwrap() function has 4 parameters among which last two are optional.
      • The parameter string is the string to be wrapped.
      • The parameter width is the maximum number of characters one row can contain.
      • The parameter break is the tag or character using which the line can be broken. Examples of characters that can be used to break a line are html break tag or \n.
      • The parameter cut if is set to true, wraps the string before or at the specified position. So that the word larger than the given width is broken apart.
      • Example of trim() and wordwrap():
      • Write the following code to demonstrate trim() and wordwrap() in the index.php file:

      <title>PHP String Functions</title>
      <h6>demonstration of:</h6>
      	//demonstration of trim()
      	echo "<strong>7) trim()</strong><br>";
      	$s2="		Today holihay, have fun!";
      	echo "<strong>".trim($s2,"\t")."</strong><br><br>";
      	//demonstration of wordwrap()
      	echo "<strong>8) wordwrap()</strong><br>";
      	$s3="Penguins are found in polar regions.";
      	echo "<strong>".wordwrap($s3,8,"<br>",true)."</strong>";
      • In the above code, we have demonstrated the trim() and wordwrap() functions.
      • In the string stored in variable $s2 we have given 2 tab spaces before the string, but still when the string is displayed using trim() function, all the spaces before and after the string are erased.
      • This trim() function is more useful to erase the both side spaces of the input given by the user.
      • When we tried to wrap the string in variable $s3 according to width 8, the string is broken using html brake tag.
      • The output is shown below:
      • trim_wordwrap_func_output
        fig 4

9. strcmp():

  • The strcmp() function is the case-sensitive function used to compare two strings.
  • When 2 strings given in strcmp() function are equal, it returns zero (0).
  • It returns value less than zero if the first string is less than the second string and it returns value greater than zero if the first string is greater than second string.
  • It gives such results because it compares the ASCII values of the characters of the string to one another.
  • Syntax of strcmp() function is:
  • strcmp(first string, second string);

10. md5():

  • The md5() function is used to calculate Message-Digest Algorithm hash of a string.
  • I mean using the md5 algorithm, the given string is converted to a 32 bit hexadecimal format.
  • The md5() function uses RSA Data Security, Inc. MD5-Message Digest Algorithm for conversion of the string.
  • Syntax of md5() function is given below:
  • md5(string, raw);
  • The md5() function has 2 parameters of which the second in optional.
  • The parameter string is the string that is to be converted to the hexadecimal or binary format.
  • The optional parameter raw has 2 values, true and false.
  • If it is given as true, then the string is converted to a 16 character binary format.
  • And if raw parameter is given as false, then the string is converted to a 32 character hexadecimal number.
  • By default its value is false.
  • Example of strcmp() and md5():
  • Write the following code to demonstrate strcmp() and md5() in the index.php file:

    <title>PHP String Functions</title>
    <h6>demonstration of:</h6>
    	//demonstration of strcmp()
    	echo "<strong>9) strcmp()</strong><br>";
    		echo $st1." is equal to ".$st2."<br><br>";
    	else if($r<0)
    		echo $st1." is less than ".$st2."<br><br>";
    		echo $st1." is greater than ".$st2."<br><br>";
    	//demonstration of md5()
    	echo "<strong>10) md5()</strong><br>";
    	echo "md5 binary equivalent of ".$st3." = ".md5($st3,true)."<br>";
    	echo "md5 hex equivalent of ".$st3." = ".md5($st3,false);
    • In the above code we have compared strings “welcome” and “Welcome” using strcmp() function.
    • This function compares the ASCII values of each character in the strings and outputs the value accordingly.
    • In the above example the first string is greater than the second string because the ASCII value of ‘w’ is greater than the ASCII value of ‘W’.
    • Next the string “Richa123” is converted to its binary as well as hexadecimal equivalent using the md5() function.
    • The binary value is 16 characters long and the hex value is 32 characters long.
    • This can be used to make some values non-understandable. For example passwords.
    • The output of both strcmp() and md5() is shown below:
    • strcmp_md5_func_output
      fig 5

11. explode():

  • The explode() function is used to break a string into number of substrings and these are stored into an array.
  • Syntax of explode() function is given below:
  • explode(string_separator, string, limit);
  • It takes 3 parameters as follows:
  • The parameter string_separator is the delimitor used to separate the string. For example a blank space.
  • The parameter string is the string that is to be broken down into substrings.
  • The parameter limit is an optional parameter.
  • If it is a positive number, then the array formed contains that many number of strings and the rest of the remaining strings are contained in the last element.
  • If it is a negative number, then all components except the last element are returned.
  • If it has value zero (0), then it is treated as 1.

12. implode():

  • The implode() function is used to reverse the work done by explode() function.
  • It means implode() function is used to join the array elements into a string.
  • Syntax of implode() function is given below:
  • implode(string_separator, array);
  • It has 2 parameters of which first one is optional and second is mandatory.
  • The parameter string_separator is to specify as to use which delimitor to separate the substrings in the string.
  • The parameter array is the array whose elements will be joined into a single string.
  • Example of explode() and implode():
  • Write the following code to demonstrate explode() and implode() in the index.php file:

    <title>PHP String Functions</title>
    <h6>demonstration of:</h6>
    	//demonstration of explode()
    	echo "<strong>11) explode()</strong><br>";
    	$s4="You can WIN!";
    	print "string = <strong>".$s4."</strong><br>";
    	print_r(explode(" ",$s4));
    	echo "<br><br>";
    	//demonstration of implode()
    	echo "<strong>12) implode()</strong><br>";
    	echo "string format = <strong>".implode(" ",$arr)."<strong>";
    • Here, in the above example a string “You can WIN!” is broken down and stored in an array using the explode() function.
    • The print_r() function is mainly used to print arrays in the array format itself i.e. along with the index and its value.
    • So we have used print_r() function to print the output of explode function.
    • Next we have an array pointed by $arr variable. We want the array elements to be joined into a single string. This is done using implode() function.
    • The output is shown below:
    • explode_implode_func_output
      fig 6

  • Some more string functions:
  • String Function Syntax Example Description
    addcslashes() addcslashes(string,characters); $str=addcslashes(“What is your AC id”,’C’); The function addcslashes() will add a backslash before the character ‘C’ and return the string as “What is you’re A\C id”.
    convert_uudecode() convert_uudecode(encrypted string); $enstr=”[email protected]#45Fg”;
    The function convert_uudecode() decodes the encrypted form of a string again to the original string.
    convert_uuencode() convert_uuencode(string); $str=”Hello Everybody”;
    The function convert_uuencode() encodes the given original string to an encrypted format.
    str_replace() str_replace(find,replace,string,count); echo str_replace(“Hello”,”Hi”,”Hi Dear”); This function is used to replace the found strings given in the string. The parameter find contains the string(s) to be searched, replace contains the string(s) to be replaced, string is the given string and count counts the number of replacements done.
    str_split() str_split(string,length); $str=”You are Welcome”;
    This function splits a string into small substrings according to the length given and stores it into an array similar to explode() function. By default it takes length 1.
    str_word_count() str_word_count(string); $w=str_word_count(”How many words are there in the given string?”); This function counts the number of words in the given string.

    These are some of the more string functions, there are many such functions.

    Thus we studied some of the important string functions that will be useful in string manipulations in this PHP String Functions tutorial.


    Please enter your comment!
    Please enter your name here