String Functions in PHP With Example

String functions in php with example - PHP provides more than 90 functions for string manipulation. Functions
String in PHP can be found at http://ca.php.net/manual/en/ref.strings.php.
Some commonly used string manipulation functions include:
  • addslashes() - adds backslashes (\) in each quotes (quote)in string.
  • chr() - produces characters from ASCII numbers
  • crypt() - produces a unencrypted string in the same direction.
  • echo() - displays one or more strings.
  • explode() - breaks a string by a delimiter (separator).
  • htmlentities() - converts all html tags into HTML entities.
  • htmlspecialchars() - converts all special characters into HTML Entities
  • implode() - merges an array element into a string with a delimiter (separator).
  • join() - the same as implode()
  • ltrim() - deletes a certain character ("", \ t, \ n, \ r, \ 0, \ x0B) at the beginning of the string.
  • md5() - produces a unencrypted string in the same direction.
  • nl2br() - adds an HTML line break (<BR>) before all newlines in string.
  • number_format() - set the number format.
  • ord() - generates ASCII code of a character.
  • rtrim() - deletes certain characters ("", \ t, \ n, \ r, \ 0, \ x0B) at the end string.
  • split() - the same as explode
  • str_repeat() - repeating the string
  • str_replace() - replaces all strings in a pattern into a string.
  • strip_tags() - ignores HTML and PHP tags in strings.
  • stripslashes() - removes backslashes (\) in strings.
  • strlen() - calculates the length of the string.
  • strpos() - finds the first position of a string in a string.
  • strrchr() - searches for the last position of a character in a string.
  • strrpos() - searches for the last position of a string in a string.
  • strrev() - inverts the string.
  • strstr() - searches for the first position of a character in a string.
  • strtolower() - converts the string to lower case.
  • strtoupper() - converts the string into uppercase (upper-case)
  • substr() - truncates the string
  • trim() - deletes certain characters ("", \ t, \ n, \ r, \ 0, \ x0B) at the end and ending.
  • ucfirst() - change the first letter of all strings to Upper-case.
  • ucwords() - change the first letter of each word in string to uppercase.
  • wordwrap() - truncates a number of characters in string with stringbreak-character.

String Functions in PHP With Example

Program 1
File Name: string03.php
Description: The program uses the functions of strtolower, strtoupper, ucfirst, ucwords, strrev, and strlen in strings.
Open notepad, then type this php code.
<?php
$str = "Everything i do, i do it for YOU";

echo "<b>The original string</b> : $str";
echo "<br><b>strtolower()</b> : ". strtolower($str);
echo "<br><b>strtoupper()</b> : ". strtoupper($str);
echo "<br><b>ucfirst() :</b> ". ucfirst($str);
echo "<br><b>ucwords() :</b> ". ucwords($str);
echo "<br><b>strrev() :</b> ". strrev($str);
echo "<br><b>Number of characters</b> : ". strlen($str);
?>

String Functions in PHP With Example

Save the php code with the name string03.php in the htdocs folder.
Program Explanation 1
Some of the functions used in program 1 above include:
  • strtolower, to convert the string into lower-case.
  • strtoupper, to convert the string into upper-case.
  • ucfirst, to change the first letter of the string to upper-case.
  • ucwords, to change the first letter of each word to upper-case.
  • strrev, to flip the string.
  • strlen, to calculate the length of the string.
To see the result open the browser then type http://localhost/string03.php in the address bar, then enter. Then the result will look like the following.
String Functions in PHP With Example
Program view

Program 2
File Name: string04.php
Description: The program uses the functions of addslashes and stripslashes on the string.
<?php
$str = "Is your name O'Reilly ?";
$str2 = addslashes ($str);
$str3 = stripslashes ($str2);

echo "<b>The original string</b> : $str";
echo "<br><b>addslashes()</b> : $str2";
echo "<br><b>stripslashes()</b> : $str3";
?>

String Functions in PHP With Example

Program Explanation 2
In program 2 above there is an addslashes() function that will add backslashes (\) to each quote in the string, and otherwise the stripslashes function will remove backslashes on the string.
String Functions in PHP With Example
Program view

Program 3
File Name: string05.php
Description: The program uses usichr to display 256 ASCII characters.
<?php
echo "Displays ASCII numbers";
for ($i=1; $i<=256; $i++) {
 echo "<br>$i.\t". chr($i);
}
?>

String Functions in PHP With Example

Program Explanation 3
Program 3 above will feature 256 ASCII characters. At line 4, there is a chr() function that will convert the $i (integer) value to ASCII characters.
String Functions in PHP With Example
Program view

Program 4
File Name: string06.php
Description: The program uses the functions of strip_tags, htmlspecialchars, and htmlentities to organize HTML tags.
<?php
$str = "<b><u>Everything I do, I do it for you</u></b>";

echo $str."<br>";
//no tag html
echo strip_tags ($str). "<br>";
//allow tag <u>
echo strip_tags ($str,"<u>")."<br>";
// Appear as it is
echo htmlspecialchars ($str)."<br>";
// Appear as it is
echo htmlentities ($str);
?>

String Functions in PHP With Example

Program Explanation 4
Program 4 above is an example of using the functions strip_tags, htmlspecialchars and htmlentities to handle HTML tags in the string. On line 6, the strip_tags function will remove all HTML tags. At line 8, strip_tags function with additional parameter "<u>" will remove all HTML tags except <u> tag. On line 10 and 12, the htmlspecialchars and htmlentities function will convert all HTML tags into special HTML characters, so HTML will be displayed as is.
String Functions in PHP With Example
Program view

Program 5
File Name: string 07.php
Description: The program uses the number_format function to set the display format of a number.
<?php
$number = 1234.56;
// english notation (default)
$english_format_number = number_format($number);
echo "<br>".$english_format_number; // 1,235
// French notation
$nombre_format_francais = number_format($number, 2, ',', ' ');
echo "<br>".$nombre_format_francais; // 1 234,56
//indonesian notation
$format_indonesia = number_format ($number, 2, ',', '.');
echo "<br>".$format_indonesia; //1.234,56
$number = 1234.5678;
// english notation without thousands seperator
$english_format_number = number_format($number, 2, '.', '');
echo "<br>". $english_format_number; // 1234.57
?>

String Functions in PHP With Example

Program Explanation 5
Program 5 above is an example of using the number_format function to set the number display. By default, the number_format function will format the numbers with the English model ie every three digits separated by commas (,) and without fractions. At line 9, the number_format function will change the number format with 2 fraction digits (the second parameter), fractions separated by commas (third parameter) and every three digits separated by spaces (fourth parameter).
String Functions in PHP With Example
Program view

Program 6
File Name: string08.php
Description: The program uses the explode function to break a string into an array.
<?php
// Example 1
$buah = "Banana peel rambutan apple orange kedondong";
$buahan = explode(" ", $buah);
echo $buahan[0]."<br>"; // mango
echo $buahan[3]."<br>"; // apple
// Example 2
$data = "foo:*:1023:1000::/home/foo:/bin/sh";
list($user, $pass, $uid, $gid, $gecos, $home, $shell) =
explode(":", $data);
echo $user."<br>"; // foo
echo $pass; // *

?>

String Functions in PHP With Example

Program Explanation 6
Program 6 above is an example of using the explode function to break a string based on a particular pattern (rule). On line 4, the explode () function will break the $fruit string based on a space and each will be the $fruits array element.
String Functions in PHP With Example
Program view

Program 7
File Name: string09.php
Description: The program uses an implode function to merge an array into a string.
<?php
$fruits = array('mango','orange','rambutan','apple','pineapple');
$fruit = implode(",", $fruits);

echo "I like fruit ". $fruit;
// mango, orange, rambutan, apple, pineapple
?>

String Functions in PHP With Example

Program Explanation 7
Program 7 above is an example of the use of the implode () function to merge all the contents of the array into a single string. The implode function is the reverse of the explode function. On the 3rd line, the implode () function will merge each $fruits array element into a $fruit string with a comma separation between each element.
String Functions in PHP With Example
Program view

Program 8
File Name: string10.php
Description: The program uses the functions of strstr, strchr and strrchr to extract some strings based on a particular pattern (character).
<?php
$file = "test.this.txt";
$ext1 = strstr($file, ".");
$ext2 = strchr($file, ".");
$ext3 = strrchr($file, ".");

echo $ext1. "<br>";  //.this.txt
echo $ext2. "<br>";  //.this.txt
echo $ext3;    //.txt
?>

String Functions in PHP With Example

Program Explanation 8
Program 8 above is an example of taking a partial string based on a certain pattern (character). The strstr and strchr functions on the 3rd and 4th rows will take the string after the point character (.) Where the search is done from the beginning of the string. While the strrchr function, will take the string after the point character (.) Which search is done from the end of the string.
String Functions in PHP With Example
Program view

Program 9
File Name: string11.php
Description: The program uses the wordwrap function to truncate a number of characters from a string.
<?php
$text = "The quick brown fox jumped over the lazy dog.";
$newtext = wordwrap($text, 15, "<br>");

echo $text."<br><br>";
echo $newtext;
?>

String Functions in PHP With Example

Program Explanation 9
Program 9 above is an example of using the wordwrap function to truncate a number of characters from a string. On line 3, the wordwrap function will truncate the $ text string per -15 characters and separated (added) with the string "<br>".
String Functions in PHP With Example
Program view

Program 10
File Name: string12.php
Description: Program usage of function nl2br in string.
<form action="" method="post">
 Input text here :<br>
 <textarea name="input" cols="40" rows="4"></textarea><br>
 <input type="submit" name="Submit" value="Proses">
</form>

<?php
if (isset($_POST['Submit'])) {
$txt = $_POST['input'];
 echo "<u>Without nl2br() :</u> <br>$txt<br><br>";
 echo "<u>With nl2br :</u> <br>". nl2br ($txt);
}
?>

String Functions in PHP With Example

Program Explanation 10
Program 10 above is an example of using the function nl2br. The function nl2br () will add the characters moved in line (<br>) at the beginning of the line of the input string. To try the above program, inputkan string as follows:
When it's written for me
Is the best for me
I made you a memory
The most beautiful of my life
But not easy for me
Left my life trail
Which is eternally carved
As the most beautiful memories
String Functions in PHP With Example
Program view

Program 11
File Name: string13.php
Description: Programs use substr functions to truncate strings.
<form action="" method="post">
Your Number :
 <input type="text" name="txtnim"><br>
 <input type="submit" name="Submit" value="Proses">
</form>

<?php
if (isset($_POST['Submit'])) {
$number = $_POST['txtnim'];
$a = substr ($number, 2, 2);
switch($a) {
  case '11' : $department = "Technical Information";
  break;    
  case '22' : $department = "Information Systems";
  break;    
  case '33' : $department = "Computer system";
  break;   
  case '44' : $department = "Computerized accounting";
  break;    
  default : $department = "The wrong direction";
}
 echo "Your Number : $number<br>";
 echo "Your Department : $department";
}
?>

String Functions in PHP With Example

Explanation of Program 11
Program 11 above is an example of using the substr function (line 10) to truncate strings. On the 10th line, the string $number will be deducted from the 2nd index character (index starts from 0) as long as 2 characters.
String Functions in PHP With Example
Program view

That explanation from me about String functions in php with example, hopefully that explanation can increase our knowledge in studying php programming language. Learn also articles about Write String in PHP.

Comments