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.
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 |
Syntax: Array explode(string $delimiter, string $toexplode, [int $limit]);
<?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 )
String implode([string $delimiter],array $exploded);
<?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 ?>
array str_split(str $to_split, [int $length])
<?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] => ! ) ?>
string trim(string $totrim, [string $strippedlist])
<?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 ?>
string str_pad(string $to_pad, int $desired_length, [string $padding_char], [int $pad_side])
<?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!____ ?>
string addslashes(string $noslashes)
<?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< ?>
string stripslashes(string $slashed)
<?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" ?>
string strip_tags(string $with_tags, string $allowed_tags)
<?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" ?>
string substr(string $string, int $start, [int $length]
<?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 ?>
int strpos(string $haystack, string $needle, [int $offset])
<?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! ?>
<?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! ?>
string strstr(string $haystack, string $needle, [bool $before])
<?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 >?>
string stristr(string $haystack, string $needle, [bool $before])
<?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 ?>
mixed str_replace(mixed $find, mixed $replace, mixed $string, [int $counter])
<?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 ) ?>
mixed str_ireplace(mixed $find, mixed $replace, mixed $string, [int $counter])
<?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. ?>