PHP String Functions


What are String Functions?

String functions are built-in language constructs and functions that are designed to manipulate and display strings. These functions include trimming whitespace, properly escaping strings for security, splitting strings, and many more. This will act as more of a reference than a complete tutorial, as there are many functions to cover. It will include proper usage, a description of what the function does, as well as what the function returns under normal circumstances.

Notes

  • The square brackets [] denote an optional parameter.
  • The word before the function name denotes the default return type, e.g. array, string, int.
  • When at all possible, use triple equals(===) with these functions, as some may return more than one type.
  • Delimiters are special characters used to separate parts of a string. Common delimiters are:
    Delimiter Description
    { and } Curly braces
    ( and ) Parentheses
    [ and ] Square brackets
    < and > Angle brackets
    " and " Double quotes for string literals
    ' and ' Single quotes for string literals
    <? and ?> Used for preprocessing directions
    , Comma
    " " Space
    \r Carriage return
    \n Newline
    \t tab
    \t tab
    \0 NULL terminator
    \x0B Vertical tab
    Please note that delimiters can be any character, these are simply the most common ones.

Array String Functions

These functions are used to convert strings to arrays, and vice-versa

  • Explode

    • The explode function splits a string by a given delimiter and returns an array with all the substrings between the delimiters
    • Syntax:    Array explode(string $delimiter, string $toexplode, [int $limit]);
    • Parameters:
      • string $delimiter: What character you want to split the string by.
      • string $toexplode: The original string that you want to turn into an array.
      • int $limit: the maximum amount of substrings you want the original string split into. If the limit is unspecified the function will return all of the substrings possible. If it is negative, it will return the maximum number of substrings minus the number specified in $limit.
      Possible return types:
      • If the delimiter exists in the string, it will return an array of strings
      • If the delimiter does not exist, and limit is positive, it will return an array with the original string.
      • If the delimiter does not exist, and the limit is negative, it will return an empty array.

      Examples:

      <?php
      	$str="Toyota,BMW,Honda,Mercedes,Bugatti,Lamborghini,Acura,Porsche";				
      	$exploded=explode(",",$str); //Limit is unspecified, so it will return all the substrings;	
      	print_r($exploded) //Print the array to the screen;
      ?>
      //Returns:
      Array
      (
          [0] => Toyota
          [1] => BMW
          [2] => Honda
          [3] => Mercedes
          [4] => Bugatti
          [5] => Lamborghini
          [6] => Acura
          [7] => Porsche
      )
      					
      <?php
      	$str="Toyota,BMW,Honda,Mercedes,Bugatti,Lamborghini,Acura,Porsche";				
      	$exploded=explode(",",$str,5); //Limit is positive, so it will return the first 5, then tack on the rest to the last array element;	
      	print_r($exploded) //Print the array to the screen;
      ?>
      //Returns:
      Array
      (
          [0] => Toyota
          [1] => BMW
          [2] => Honda
          [3] => Mercedes
          [4] => Bugatti,Lamborghini,Acura,Porsche
      )
      					
      <?php
      	$str="Toyota,BMW,Honda,Mercedes,Bugatti,Lamborghini,Acura,Porsche";				
      	$exploded=explode(",",$str,-3); //Limit is negative, so it will find all the substrings
      	print_r($exploded) //Print the array to the screen;
      ?>
      //Returns:
      Array
      (
          [0] => Toyota
          [1] => BMW
          [2] => Honda
          [3] => Mercedes
          [4] => Bugatti
      							
      )
      
      					
  • Implode

    • The implode function does the exact opposite of the explode function. It converts an array into a string, with each array element separated by a delimiter.
    • String implode([string $delimiter],array $exploded);
    • Parameters:
      • string $delimiter: The character that you want the array element to be joined by. If unspecified, default "", or empty string.
      • $array exploded: The array of strings that you want to join by the delimiter
      Return Values:
      • A string of all the array elements joined together.

      Examples

      <?php
      		$array=Array
      	(	
      		[0] => Toyota
      		[1] => BMW
      		[2] => Honda
      		[3] => Mercedes
      		[4] => Bugatti
      		[5] => Lamborghini
      		[6] => Acura
      		[7] => Porsche
      	)
      	$string=implode(", " $array); //Implode the array into a string, split by the delimiter ", ";
      	echo $string;
      	//Returns
      	Toyota, BMW, Honda, Mercedes, Bugatti, Lamborghini, Acura, Porsche	
      ?>			
      				
  • str_split

    • The str_split function takes a string to turn into an array, and splits the string into an array, with each of the characters being a separate character.
    • array str_split(str $to_split, [int $length])
    • Parameters:
      • string $to_split: The string you want to split into an array
      • int $length: The length of each array element. Default is one, so it splits a string into every character
      Return Values:
      • If $length is greater than one, an array is returned
      • Otherwise, it returns FALSE

      Examples:

      <?php
      	$to_split="Hello, World!";
      	print_r(str_split($to_split)); //No length specified, so it will split each character into an array element
      	
      	//Returns:
      	
      	Array
      (
          [0] => H
          [1] => e
          [2] => l
          [3] => l
          [4] => o
          [5] => ,
          [6] =>  
          [7] => W
          [8] => o
          [9] => r
          [10] => l
          [11] => d
          [12] => !
      )
      				
      ?>
      <?php
      	$to_split="Hello, World!";
      	print_r(str_split($to_split),2); //Length specified, so it will split it ever two characters.
      	
      	//Returns:
      	
      	Array
      (
          [0] => He
          [1] => ll
          [2] => o,
          [3] =>  W
          [4] => or
          [5] => ld
          [6] => !
      )
      				
      ?>

Adding and Removing Special Characters

These functions are used to add and remove special characters, such as slashes, quotation marks, angle brackets, ampersands, and whitespace. This is often done to improve security, especially when dealing with mySQL databases, which are up in the ranks with Java applets as things that a baby could hack, when not protected properly.

  • trim

    • The trim() function removes whitespace characters from the beginning and end of a string on default settings, but can also remove other characters if specified
    • string trim(string $totrim, [string $strippedlist])
    • Parameters:
      • string $totrim: The string with characters you want to strip off of the ends
      • string $strippedchars: The list of characters to trim off the ends. Default is all the whitespace characters ("\t\n\r\0\x0B"). To refresh your memory on that, please refer to the delimiters table. However, you can trim any ASCII character by specifying it in the optional strippedchars parameter.
      Return Values:
      • This will always return a string. Even if there are no characters to be stripped, it will return the same string you passed into it.

      Examples:

      <?php
      //Trimming a string using the default settings, only trimming whitespace
      
      $string="\tHello\t\nWorld!\n"; //Equivalent to (tab)Hello(tab)(line break)World!(line break) 
      echo $string;
      
      //Returns
      	Hello	
      World!
      
      echo trim($string); //Notice it only trims the tabs and newlines on the ends of the string, not the newline between Hello and World
      
      //Returns
      Hello	
      World!
      ?>
      
      				
      <?php
      	//Trimming a string using custom characters
      	$string="Hello, World!";
      	echo $string;
      	//Returns
      	Hello, World!	
      	$trimmed=trim($string,"HoWdy!");
      	echo $trimmed; //As you can see, it cuts off all the characters off the end, but leaves the o in the middle.
      	
      	
      	//Returns
      	
      	ello, Worl
      ?>
      				
  • rtrim and ltrim

    • These are the same as trim, except they only do it from one end. rtrim trims from the end, and ltrim trims form the beginning. The syntax is the same, as follows.
    • string ltrim(string $totrim, [string $strippedlist])
    • string rtrim(string $totrim, [string $strippedlist])
  • str_pad

    • str_pad adds characters to the ends of string to make it a certain length
    • string str_pad(string $to_pad, int $desired_length, [string $padding_char], [int $pad_side])
    • Parameters:
      • string $to_pad: The input string that you want to pad to the int $desired_length
      • string $padding_char: The character that you want to pad the string with. Default is one empty space (" ").
      • int $pad_side: The side that you want to pad with. Default is STR_PAD_RIGHT. It can also be STR_PAD_LEFT and STR_PAD_BOTH
      Return Values:
      • Returns a string padded to the appropriate length. If the desired length is less than the length of the string or less than one, the function will return the same string.

      Examples:

      <?php
      		//Padding on default settings
      	$string="hello, world!"; //14 chars
      	$padded=str_pad($string,20); //20 chars
      	echo $string . "||text has ended"; // the "||text has ended" is to show where the padding takes it, since whitespace is invisible
      	echo $padded . "||text has ended";
      
      	//Returns 
      	hello, world!||text has ended	
      	hello, world!       ||text has ended	
      
      ?>
      
      <?php
      		//Padding on default settings, changing the padding character
      	$string="Hello, World!"; //14 chars
      	$padded=str_pad($string,20,"__"); //20 chars
      	echo $string."<br>";
      	echo $padded;
      
      	//Returns 
      	hello, world!	
      	hello, world!_______	
      
      ?>
      
      <?php
      	
      	//Padding on default settings
      	$string="hello, world!"; //14 chars
      	$paddedleft=str_pad($string,20,"__",STR_PAD_RIGHT); //20 chars
      	$paddedright=str_pad($string,20,"__",STR_PAD_RIGHT); //20 chars
      	$paddedboth=str_pad($string,20,"__",STR_PAD_BOTH); //20 chars
      	echo $paddedleft."<br>";
      	echo $paddedright."<br>";
      	echo $paddedboth;
      
      	//Returns 
      	
      	hello, world!_______	
      	hello, world!_______	
      	___hello, world!____
      ?>
      
  • addslashes

    • This function takes one input string and returns a string with all of the quotation marks escaped by a slash.
    • This is used any time anyone ever enters anything into a database. If you do not do this, you will end up just like Bobby Table's school. Because the name was not escaped in the database, the quotation mark made the database think that it was a command.

    • Little Bobby Tables broked it
    • If they had used addslashes, they would not have lost all the student records. EVERY TIME YOU ENTER SOMETHING INTO A DATABASE, MAKE SURE IT IS PROPERLY ESCAPED.
    • string addslashes(string $noslashes)
    • Parameters:
      • string $noslashes: An unescaped string, such as the following: "I am about to land at O'Hare airport"
      Return Values:
      • You will get a properly escaped string, such as the following: "I am about to land at O\'Hare airport"

      Examples:

      <?php
      	$string="I am about to land at O'Hare airport in Chicago, Illinois";
      	echo $string;
      	echo addslashes($string); //As you can see, in the first one, the string breaks in the middle, because of the stray quotation mark.	
      	//Returns:	
      	
      	
      	I am about to land at O'Hare airport in Chicago, Illinois
      	I am about to land at O\'Hare airport in Chicago, Illinois<
      	
      ?>
  • stripslashes

    • This function is often used when retrieving information from a database, to display it correctly on a screen, because all database contents should be escaped properly.
    • string stripslashes(string $slashed)
    • Parameters:
      • string $slashed: A string properly escaped like this on: "I am about to land at O\'hare Airport"
      Return values:
      • An unescaped string, like this one: "I am about to land at O'Hare airport

      Examples:

      <?php
      	$string="I am about to land at O\'Hare airport in Chicago, Illinois";
      	echo $string;
      	echo stripslashes($string);
      	//Returns:	
      	
      	"I am about to land at O\'Hare airport in Chicago, Illinois"
      	"I am about to land at O'Hare airport in Chicago, Illinois"
      ?>
  • strip_tags

    • strip_tags is another security feature, to prevent people from entering HTML tags into forms. This is useful because otherwise, people could enter new forms, and submit them, as well as Javascript, and Iframes containing malicious code. You can, however, allow certain more harmless tags, such as bold tags, link tags, and paragraph tags.
    • string strip_tags(string $with_tags, string $allowed_tags)
    • Parameters:
      • string $with_tags: The raw form data that you want to cleanse
      • string $allowed_tags: TAgs that you want to allow. Simply put the tags in a string. For example, if you want to allow the p and a tag, enter this as your second parameter: '<a><p>'
      Return Values:
      • This will return a string stripped clean of all non-allowed tags.
      Examples:
      <?php
      
      	$string="<iframe src='../../../../../../'><<iframe>huehuehue<i>iwillhaxursitez</i>";
      	echo htmlentities($string); //htmlentities shows the HTML source code, not what the browser renders
      	echo htmlentities(strip_tags($string)); 
      
      
      	//returns:
      
      	<iframe src='../../../../../../'></iframe>huehuehue<i>iwillhaxursitez</i>
      huehuehueiwillhaxursitez //haxor's evil plan is foiled! ?>
      <?php
      	//Now a good user wants to come and comment on the previous person's failed attempt	to hack, but unfortunately, they cannot emphasize their point by putting things in bold. This can be fixed by editing the second parameter to the strip tags function
      	$string = "<b>hackers never prosper</b>";
      	
      	echo $string . "<br>";
      	echo strip_tags($string). "<br>";
      	echo strip_tags($string,"<b>");
      	
      	//Returns
      	
      	"hackers never prosper"
      "hackers never prosper"
      "hackers never prosper" ?>

Manipulating Substrings

These functions are used to get and manipulate different parts of string, as well as locating parts of a string inside a string

  • substr

    • substr takes a string and a location to start in that string, and returns the substring starting at the location specified going to the end of the string
    • string substr(string $string, int $start, [int $length]
    • Parameters:
      • string $string: The string you want to find a substring of
      • int $start: The location you want to start at(0 is the first character)
      • int $length: optional. The length of the substring you want.
      Return values:
      • If the string is found, then it returns a substring
      • If the string is not found, it will return false
      Examples:
      <?php
      	$string="hello, world!";
      	echo $string."\n";
      	$substring=substr($string,4);//no length specified, so it returns the rest of the string.
      	echo $substring;
      	
      	//Returns
      	
      	hello, world!
      	o, world!
      ?>
      <?php
      	$string="hello, world!";
      	echo $string."\n";
      	$substring=substr($string,-4,2);//Start is negative, so it starts at the end and goes back 4
      	echo $substring;
      	
      	//Returns
      	
      	hello, world!
      	rl
      ?>
  • strpos

    • strpos finds the location of a substring in a string. The first character in a string is character 0
    • int strpos(string $haystack, string $needle, [int $offset])
    • Parameters:
      • string $haystack: The string you want to search for the string $needle in
      • int $offset: Optional, default 0. Which character in the string you want to start the search.
      Return Values:
      • If the substring is found, it will return an integer with the position of the substring. Note that like arrays, strings start at an index of 0
      • If the substring is not found, it will return FALSE. Therefore, you must use the triple equals(===) operator, because if the substring starts at character 0, and you use double equals (==), PHP will think that FALSE==0, and may not realize that the substring is actually in the string.
      Examples:
      <?php
      	$haystack="hello, world!";
      	echo $haystack."<br>";
      	$location=strpos($haystack, "l"); //Optional parameter offset not specified, so it will find the first instance of "l"
      	echo "The character l is found at character $location in $haystack"; //Notice that it returns 2 instead of 3, since strings start at 0;
      	//Returns:
      	hello, world!
      The character "l" is found at character 2 in hello, world! ?>
      <?php
      	$haystack="hello, world!";
      	echo $haystack."<br>";
      	$location=strpos($haystack, "l",5); //Optional parameter offset specified, so it will return the first instance of "l" after character 6
      	echo "The character l is found at character $location in $haystack"; 
      	//Returns:
      	hello, world!
      The character l is found at character 10 in hello, world! ?>
      <?php
      	$haystack="hello, world!";
      	echo $haystack."<br>";
      	$location=strpos($haystack, "h");//Demonstration to show you why to always use !== and === when possible, because 0 is falsy
      	if($location!=false){
      		echo "The character h is found at character $location in $haystack"; 
      	}else{
      		echo "The character h is not found in $haystack";
      	}
      	//Returns:
      	hello, world!
      The character h is not found in hello, world! ?>
      <?php
      	$haystack="hello, world!";
      	echo $haystack."<br>";
      	$location=strpos($haystack, "h");//However, if you use !== and ===
      	if($location!==false)
      		echo "The character h is found at character $location in $haystack"; 
      	}else{
      		echo "The character h is not found in $haystack";
      	}
      	//Returns:
      	hello, world!
      The character h is found at character 0 in hello, world! ?>
  • stripos

    • stripos does the same thing as strpos, except that it is case-insensitive. The syntax and parameters are exactly the same as strpos
    • Examples:
      <?php
      	$haystack="hello, world!";
      	echo $haystack."<br>";
      	$location=stripos($haystack, "L"); //L is not in the string, but "l" is so you need a case insensitive search.
      	echo "The character L is found at character $location in $haystack"; //Notice that it returns 2 instead of 3, since strings start at 0;
      	//Returns:
      	hello, world!
      The character "L" is found case insensitively at character 2 in hello, world! ?>
  • strstr

    • strstr takes a string to look in, a string to look for, and returns all of the characters before or after the string you want to look for
    • string strstr(string $haystack, string $needle, [bool $before])
    • Parameters:
      • string $haystack: The string you want to look for the string $needle in
      • bool $before: Optional, default false. If true, it will return the substring before the needle, if false, it will return the substring after the needle. Note that this was added in PHP 5.3.0, and as of this moment, July 11, 2013, Shodor servers are running PHP 5.1.6, this will not work. However, in the example below, I have shown how to work around this in the examples below, by combining strpos with substr
      Return Values:
      • If the needle is found, it returns a substring.
      • If the needle is not found, it returns FALSE
      Examples:
      <?php
      	$haystack="foo@bar.com";
      	echo $haystack."<br>";
      	$domain=strstr($haystack,"@");
      	echo $domain;	
      	
      	//Returns:
      	
      	foo@bar.com
      @bar.com ?>
      <?php
      	
      	//Note that you should not use this to validate email addresses, since it is very unreliable. For more information, see my regex tutorial.
      	$haystack="foo@bar.com";
      	echo $haystack."<br>";
      	$username = substr($haystack, 0, strpos($haystack, "@"));
      	echo $username;	
      	
      	//Returns:
      	
      	foo@bar.com
      foo ?>
  • stristr (case insensitive strstr)

    • stristr takes a string to look in, a string to look for, and returns all of the characters before or after the string you want to look for
    • string stristr(string $haystack, string $needle, [bool $before])
    • Parameters:
      • string $haystack: The string you want to look for the string $needle in, and it doesn't matter what case the needle or haystack is in.
      • bool $before: Optional, default false. If true, it will return the substring before the needle, if false, it will return the substring after the needle. Note that this was added in PHP 5.3.0, and as of this moment, July 11, 2013, Shodor servers are running PHP 5.1.6, this will not work. However, in the example below, I have shown how to work around this in the examples below, by combining strpos with substr
      Return Values:
      • If the needle is found, it returns a substring.
      • If the needle is not found, it returns FALSE
      <?php
      	$haystack="FoO@bAr.cOm";
      	$needle="@Ba";
      	$substring=stristr($haystack,$needle);
      	echo "$haystack <br> $substring";  //See? Case doesn't matter
      	
      	//Returns:
      	
      ?	FoO@bAr.cOm 
      @bAr.cOm ?>
  • str_replace

    • str_replace replaces certain substrings in a string with other substrings. It takes an array of strings or a single string to search for, an array of strings or a single string to replace it with, an array of strings or a single string that needs replacing, and a counter for the number of replacements you want to happen, and returns a string or an array
    • mixed str_replace(mixed $find, mixed $replace, mixed $string, [int $counter])
    • Parameters:
      • mixed $find: An array or string to search for
      • mixed $replace: An array or string to replace the $find with
      • mixed $string: The string to do all the replacements in
      • int $count: The number of replacements you want to do
      Notes:
      • When both $find and $replace are arrays, it will go from first to last, and replace the first element of the find array with the first element of the replace array, and so on and so forth
      • When both $find and $replace are strings, it replaces all of the $finds in the string with $replaces
      • If $find is an array and $replace is a string, then it will replace all of the strings in $find with $replace
      • $find cannot be a string while $replace is an array
      Return values:
      • If $string is an array, it returns an array
      • If $string is a string, it returns a string
      Examples:
      <?php
      	$string="hello. My name is bob. This is my friend bob.";
      	$find="bob";
      	$replace="joe";	
      	$result=str_replace($find,$replace,$string); //No limit specified, so it will change all the bobs to joes.     
      	echo $string."<br>".$result;
      	
      	//Returns
      	
      	
      	hello. My name is bob. This is my friend bob.
      hello. My name is joe. This is my friend joe. ?>
      <?php
      	$string="hello. My name is bob. This is my friend bob.";
      	$find=Array("bob","friend"); 
      	$replace=Array("joe","enemy"); //Because there are two arrays, it will replace bob with joe, and friend with enemy.
      	$result=str_replace($find,$replace,$string); //No limit specified, so it will change all the bobs to Joes.     
      	echo $string."<br>".$result;
      	
      	//Returns
      	
      	
      	hello. My name is bob. This is my friend bob.
      hello. My name is joe. This is my enemy joe. ?>
      <?php
      	$string="hello. My name is bob. This is my friend bob.";
      	$find=Array("bob","friend");
      	$replace="joe";	//Since find is an array, and replace is not, it will replace all the elements of $find with $replace
      	$result=str_replace($find,$replace,$string);
      	echo $string."<br>".$result;
      	
      	//Returns
      	
      	hello. My name is bob. This is my friend bob.
      hello. My name is joe. This is my joe joe. ?>
      <?php
      	$strings=Array("hello. My name is bob. This is my friend bob.","Hello. My name is bill. This is my friend jill");
      	$find=Array("bob","friend","bill","jill");
      	$replace=Array("joe","worst enemy","will","jane");
      	$result=str_replace($find,$replace,$string); //Since $strings is an array, $results is an array
      	print_r($result); //Echo $result to the screen
      	
      	//Returns
      	
      	
      	Array
      (
          [0] => hello. My name is joe. This is my worst enemy joe.
          [1] => hello. My name is will. This is my worst enemy jane		
      
      )
      
      ?>
  • str_ireplace

    • str_ireplace is a case-insensitive version of str_replace
    • mixed str_ireplace(mixed $find, mixed $replace, mixed $string, [int $counter])
    • Parameters:
      • mixed $find: An array or string to search for
      • mixed $replace: An array or string to replace the $find with
      • mixed $string: The string to do all the replacements in
      • int $count: The number of replacements you want to do
      Notes:
      • When both $find and $replace are arrays, it will go from first to last, and replace the first element of the find array with the first element of the replace array, and so on and so forth
      • When both $find and $replace are strings, it replaces all of the $finds in the string with $replaces
      • If $find is an array and $replace is a string, then it will replace all of the strings in $find with $replace
      • $find cannot be a string while $replace is an array
      Return values:
      • If $string is an array, it returns an array
      • If $string is a string, it returns a string
      Examples:
      <?php
      	$string="Hi! My name is Bob.";
      	$find="bob"; //Notice that the b is lowercase here, but uppercase here
      	$replace="Joe";
      	$result=str_ireplace($find,$replace,$string);
      	echo "$string <br> $result";
      	
      	//Returns
      	
      	Hi! My name is Bob. 
      Hi! My name is Joe. ?>