11/20/2023 | News release | Distributed by Public on 11/20/2023 06:07
Published: November 20, 2023
Strings are the building blocks of data in PHP and they're essential in nearly every aspect of web development. From data parsing to text manipulation, string functions alleviate complex problems and help you build dynamic websites and applications.
This blog post explores PHP string functions, including their diverse applications and how they can save you time and effort in your coding endeavors.
Read on for a comprehensive list of PHP string functions, or check out this table of jump links to navigate to one of your choosing.
This function returns the length of a string.
Example:
<?php
$text= "Hello, World!";
$length= strlen($text);
echo"The length of the string is $length characters.";
?>
Output:
The length of the string is 13 characters.
This function finds the position of a substring in a string.
Example:
<?php
$text= "This is a test string.";
$pos= strpos($text, "test");
echo"The word 'test' starts at position $pos.";
?>
Output:
The word 'test' starts at position 10.
Similar to strpos(), this function also finds the position of a substring in a string.
Example:
<?php
$text= "This is a test string.";
$pos= stripos($text, "Test");
echo"The word 'Test' starts at position $pos.";
?>
Output:
The word 'Test' starts at position 10.
This function extracts a substring from a string.
Example:
<?php
$text= "Hello, World!";
$substring= substr($text, 0, 5);
echo"The first 5 characters are: $substring";
?>
Output:
The first 5 characters are: Hello
This function replaces all occurrences of a substring with another substring.
Example:
<?php
$text= "Hello, World!";
$newText= str_replace("World", "Universe", $text);
echo"Replaced: $newText";
?>
Output:
Replaced: Hello, Universe!
This function repeats a string a specified number of times.
Example:
<?php
$text= "La ";
$repeatedText= str_repeat($text, 3);
echo"Repetition: $repeatedText";
?>
Output:
Repetition: La La La
This function converts the first character of a string to uppercase.
Example:
<?php
$text= "hello, world!";
$capitalized= ucfirst($text);
echo"Capitalized: $capitalized";
?>
Output:
Capitalized: Hello, world!
This function converts the first character of each word in a string to uppercase.
Example:
<?php
$text= "hello, world!";
$capitalizedWords= ucwords($text);
echo"Capitalized Words: $capitalizedWords";
?>
Output:
Capitalized Words: Hello, World!
This function converts the first character of a string to lowercase.
Example:
<?php
$text= "Hello, World!";
$lowercased= lcfirst($text);
echo"Lowercased: $lowercased";
?>
Output:
Lowercased: hello, World!
This converts a string to all uppercase characters.
Example:
<?php
$text= "Hello, World!";
$uppercase= strtoupper($text);
echo"Uppercase: $uppercase";
?>
Output:
Uppercase: HELLO, WORLD!
This function converts a string to lowercase.
Example:
<?php
$text= "Hello, World!";
$lowercase= strtolower($text);
echo"Lowercase: $lowercase";
?>
Output:
Lowercase: hello, world
This removes whitespace or other characters from the beginning and end of a string.
Example:
<?php
$text= " Hello, World! ";
$trimmed= trim($text);
echo"Trimmed: $trimmed";
?>
Output:
Trimmed: Hello, World!
This function removes whitespace from the beginning of a string.
Example:
<?php
$text= " Hello, World! ";
$leftTrimmed= ltrim($text);
echo"Left Trimmed: $leftTrimmed";
?>
Output:
Left Trimmed: Hello, World!
This function removes whitespace from the end of a string.
Example:
<?php
$text= " Hello, World! ";
$rightTrimmed= rtrim($text);
echo"Right Trimmed: $rightTrimmed";
?>
Output:
Right Trimmed: Hello, World!
This function reverses the order of a string.
Example:
<?php
$text= "Hello, World!";
$reversed= strrev($text);
echo"Reversed: $reversed";
?>
Output:
Reversed: !dlroW ,olleH
This function compares two strings and returns 0 if they are equal, a positive number if the first string is greater, and a negative number if the second string is greater.
Example:
<?php
$string1= "apple";
$string2= "banana"; $result= strcmp($string1, $string2);
echo"Comparison Result: $result";
?>
Output:
Comparison Result: -1
This function performs the same task as strcmp(), however, this function is not case-sensitive.
Example:
<?php
$string1= "apple";
$string2= "Apple";
$result= strcasecmp($string1, $string2);
echo"Case-Insensitive Comparison Result: $result";
?>
Output:
Case-Insensitive Comparison Result: 0
This function performs a natural order string comparison.
Example:
<?php
$string1= "img2.png";
$string2= "img10.png";
$result= strnatcmp($string1, $string2);
echo"Natural Comparison Result: $result";
?>
Output:
Natural Comparison Result: -1
This is the case-insensitive version of strnatcmp().
Example:
<?php
$string1= "IMG2.png";
$string2= "img10.png";
$result= strnatcasecmp($string1, $string2);
echo"Case-Insensitive Natural Comparison Result: $result";
?>
Output:
Case-Insensitive Natural Comparison Result: -1
This function finds the first occurrence of a substring and returns the part of the string from that occurrence to the end.
Example:
<?php
$text= "This is a test string.";
$substring= strstr($text, "test");
echo"Found: $substring";
?>
Output:
Found: test string.
This is the case-insensitive version of strstr().
Example:
<?php
$text= "This is a test string.";
$substring= stristr($text, "Test");
echo"Found (Case-Insensitive): $substring";
?>
Output:
Found (Case-Insensitive): test string.
This function finds the last occurrence of a character and returns the part of the string from that occurrence to the end.
Example:
<?php
$text= "This is a test string.";
$substring= strrchr($text, "t");
echo"Last Occurrence: $substring";
?>
Output:
Last Occurrence: tring.
This function randomly shuffles the characters in a string.
Example:
<?php
$text= "Hello, World!";
$shuffled= str_shuffle($text);
echo"Shuffled: $shuffled";
?>
Output:
Shuffled: ldHoeWl,r ol!
This function wraps a string to a specified number of characters per line, breaking lines at word boundaries.
Example:
<?php
$text= "This is a long sentence that should be wrapped.";
$wrapped= wordwrap($text, 15, "
");
echo"Wrapped:
$wrapped";
?>
Output:
Wrapped:
This is a long
sentence that
should be
wrapped.
The explode function splits a string into an array by a specified delimiter.
Example:
<?php
$text= "apple,banana,orange";
$fruits= explode(",", $text);
print_r($fruits);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
This function joins the elements of an array into a string using a specified delimiter.
Example:
<?php
$fruits= ["apple", "banana", "orange"];
$text= implode(", ", $fruits);
echo"Fruits: $text";
?>
Output:
Fruits: apple, banana, orange
The join function is an alias for the implode() function.
Example:
<?php
$fruits= ["apple", "banana", "orange"];
$text= join(", ", $fruits);
echo"Fruits: $text";
?>
Output:
Fruits: apple, banana, orange
The string split function splits a string into an array of characters.
Example:
<?php
$text= "Hello";
$characters= str_split($text);
print_r($characters);
?>
Output:
Array
(
[0] => H
[1] => e
[2] => l
[3] => l
[4] => o
)
This function splits a string into smaller chunks and adds a delimiter.
Example:
<?php
$text= "1234567890";
$chunked= chunk_split($text, 2, "-");
echo"Chunked: $chunked";
?>
Output:
Chunked: 12-34-56-78-90-
This function puts special characters in a string to prevent SQL injection and other security vulnerabilities.
Example:
<?php
$text= "I'm using PHP's functions.";
$escaped= addslashes($text);
echo"Escaped: $escaped";
?>
Output:
Escaped: I\'m using PHP\'s functions.
This function removes slashes added by the addslashes() function.
Example:
<?php
$text= "I\'m using PHP\'s functions.";
$unescaped= stripslashes($text);
echo"Unescaped: $unescaped";
?>
Output:
Unescaped: I'm using PHP's functions.
This function creates a quote string with slashes in a C-like style.
Example:
<?php
$text= "Hello, World!";
$quoted= addcslashes($text, 'W');
echo"Quoted: $quoted";
?>
Output:
Quoted: Hello, \World!
This function converts special characters to their HTML entities.
Example:
<?php
$text= "This is bold";
$escaped= htmlspecialchars($text);
echo"Escaped: $escaped";
?>
Output:
Escaped: This is <b>bold</b>
This function converts all applicable characters to their HTML entities.
Example:
<?php
$text= "This is bold";
$escaped= htmlentities($text);
echo"Escaped: $escaped";
?>
Output:
Escaped: This is <b>bold</b>
This decodes HTML entities back to their corresponding characters.
Example:
<?php
$text= "This is <b>bold</b>";
$decoded= html_entity_decode($text);
echo"Decoded: $decoded";
?>
Output:
Decoded: This is bold
This function removes HTML and PHP tags from a string.
Example:
<?php
$text= "This is bold and italic.";
$stripped= strip_tags($text);
echo"Stripped: $stripped";
?>
Output:
Stripped: This is bold and italic.
This function decodes HTML entities back to their corresponding characters.
Example:
<?php
$text= "This is <b>bold</b>";
$decoded= htmlspecialchars_decode($text);
echo"Decoded: $decoded";
?>
Output:
Decoded: This is bold
This function inserts HTML line breaks before all new lines in a string.
Example:
<?php
$text= "This is a\nmultiline\nstring.";
$brText= nl2br($text);
echo"With Line Breaks:
$brText";
?>
Output:
With Line Breaks:
This is a
multiline
string.
This function replaces a portion of a string with another string.
Example:
<?php
$text= "Hello, World!";
$replacement= "Universe";
$newText= substr_replace($text, $replacement, 7, 5);
echo"Replaced: $newText";
?>
Output:
Replaced: Hello, Universe!
This function counts the number of non-overlapping occurrences of a substring in a string.
Example:
<?php
$text= "The quick brown fox jumps over the lazy dog.";
$count= substr_count($text, "the");
echo"Substring Count: $count";
?>
Output:
Substring Count: 1
This function searches a string for any of a set of characters and returns the portion of the string from the first occurrence of any of those characters.
Example:
<?php
$text= "ABC-123";
$portion= strpbrk($text, "0123456789");
echo"Portion: $portion";
?>
Output:
Portion: 123
This function calculates the soundex key of a string.
Example:
<?php
$text1= "Smith";
$text2= "Smyth";
$soundex1= soundex($text1);
$soundex2= soundex($text2);
echo"Soundex of '$text1': $soundex1
";
echo"Soundex of '$text2': $soundex2";
?>
Output:
Soundex of 'Smith': S530
Soundex of 'Smyth': S530
This function calculates the metaphone key of a string.
Example:
<?php
$text1= "Smith";
$text2= "Smyth";
$metaphone1= metaphone($text1);
$metaphone2= metaphone($text2);
echo"Metaphone of '$text1': $metaphone1
";
echo"Metaphone of '$text2': $metaphone2";
?>
Output:
Metaphone of 'Smith': SM0
Metaphone of 'Smyth': SM0
This performs a locale-based string comparison.
Example:
<?php
$text1= "café";
$text2= "cafe";
$result= strcoll($text1, $text2);
echo"Comparison Result: $result";
?>
Output:
Comparison Result: 94
This returns the length of the initial segment of a string that contains no characters from a given mask.
Example:
<?php
$text= "abcde12345";
$mask= "1234567890";
$length= strcspn($text, $mask);
echo"Length: $length";
?>
Output:
Length: 5
This function pads a string to a specified length with another string.
Example:
<?php
$text= "Hello";
$padded= str_pad($text, 10, ".");
echo"Padded: $padded";
?>
Output:
Padded: Hello.....
This function translates certain characters in a string.
Example:
<?php
$text= "hello, world!";
$trans= strtr($text, "lo", "12");
echo"Translated: $trans";
?>
Output:
Translated: he112, w2r1d!
This function calculates the similarity between two strings.
Example:
<?php
$text1= "hello, world!";
$text2= "world, hello!"; similar_text($text1, $text2, $percent);
echo"Similarity: $percent%";
?>
Output:
Similarity: 46.153846153846%
This function calculates the Levenshtein distance between two strings.
Example:
<?php
$text1= "kitten";
$text2= "sitting";
$distance= levenshtein($text1, $text2);
echo"Levenshtein Distance: $distance";
?>
Output:
Levenshtein Distance: 3
This calculates the 32-bit CRC (Cyclic Redundancy Check) of a string.
Example:
<?php
$text= "Hello, World!";
$crc= crc32($text);
echo"CRC32: $crc";
?>
Output:
CRC32: 3964322768
This function calculates the MD5 hash of a string.
Example:
<?php
$text= "Hello, World!";
$hash= md5($text);
echo"MD5 Hash: $hash";
?>
Output:
MD5 Hash: 65a8e27d8879283831b664bd8b7f0ad4
This function calculates the SHA-1 hash of a string.
Example:
<?php
$text= "Hello, World!";
$hash= sha1($text);
echo"SHA-1 Hash: $hash";
?>
Output:
SHA-1 Hash: 0a0a9f2a6772942557ab5355d76af442f8f65e01
This function calculates the hash value using a specified hash function.
Example:
<?php
$text= "Hello, World!";
$hash= hash('sha256', $text);
echo"SHA-256 Hash: $hash";
?>
Output:
SHA-256 Hash: dffd6021bb2bd5b0af676290809ec3a53191dd81c7f70a4b28688a362182986f
The crypt() function creates a one-way string hashing for password storage and security.
Example:
<?php
$password= "mysecretpassword";
$hashedPassword= crypt($password, '$2a$07$usesomesillystringforsalt$');
echo"Hashed Password: $hashedPassword";
?>
Output:
Hashed Password: $2a$07$usesomesillystringforeZ2/FbMazlxeaWs2I.edlhZE1aZ4Qcci
This function counts the number of words in a string.
Example:
<?php
$text= "This is a simple sentence.";
$wordCount= str_word_count($text);
echo"Word Count: $wordCount";
?>
Output:
Word Count: 5
This function formats a number as a currency string.
Example:
<?php
$amount= 12345.67;
$formatted= money_format('%i', $amount);
echo"Formatted: $formatted";
?>
Output:
USD 12,345.67
This is the case-insensitive version of str_replace(). It replaces all occurrences of a substring with another substring in a string.
Example:
<?php
$text= "Hello, world! Hello, universe!";
$newText= str_ireplace("hello", "hi", $text);
echo"Replaced: $newText";
?>
Output:
Replaced: hi, world! hi, universe!
This returns information about characters used in a string.
<?php
$text= "apple";
$info= count_chars($text, 1);
print_r($info);
?>
Output:
Array
(
[97] => 1
[101] => 1
[108] => 1
[112] => 2
)
This function parses a CSV string into an array.
Example:
<?php
$csv= "apple,banana,orange";
$array= str_getcsv($csv);
print_r($array);
?>
Output:
Array
(
[0] => apple
[1] => banana
[2] => orange
)
This function quotes meta characters in a string.
Example:
<?php
$text= "This is a (test).";
$quoted= quotemeta($text);
echo"Quoted: $quoted";
?>
Output:
Quoted: This is a \(test\)\.
This function URL-encodes a string.
Example:
<?php
$text= "Hello, World!";
$encoded= urlencode($text);
echo"Encoded: $encoded";
?>
Output:
Encoded: Hello%2C+World%21
This function decodes a URL-encoded string.
Example:
<?php
$encoded= "Hello%2C+World%21";
$decoded= urldecode($encoded);
echo"Decoded: $decoded";
?>
Output:
Decoded: Hello, World!
This function raw URL-encodes a string.
Example:
<?php
$encoded= "Hello%2C%20World%21";
$decoded= rawurldecode($encoded);
echo"Raw Decoded: $decoded";
?>
Output:
Raw Decoded: Hello, World!
This function decodes a raw URL-encoded string.
Example:
<?php
$encoded= "Hello%2C%20World%21";
$decoded= rawurldecode($encoded);
echo"Raw Decoded: $decoded";
?>
Output:
Raw Decoded: Hello, World!
This function parses a URL and returns its components.
Example:
<?php
$url= "https://www.example.com/path/file.php?param=value#fragment";
$components= parse_url($url);
print_r($components);
?>
Output:
Array
(
[scheme] => https
[host] => www.example.com
[path] => /path/file.php
[query] => param=value
[fragment] => fragment
)
This function parses a query string into variables.
Example:
<?php
$query= "param1=value1¶m2=value2";
parse_str($query, $vars);
print_r($vars);
?>
Output:
Array
(
[param1] => value1
[param2] => value2
)
This function returns a character specified by an ASCII value.
Example:
<?php
$ascii= 65; // ASCII code for 'A'
$character= chr($ascii);
echo"Character: $character";
?>
Output:
Character: A
This function generates a URL-encoded query string from an array or object.
Example:
<?php
$data= array('name'=> 'John', 'age'=> 30);
$query= http_build_query($data);
echo"Query: $query";
?>
Output:
Query: name=John&age=30
This function converts binary data into hexadecimal representation.
Example:
<?php
$binaryData= "\x48\x65\x6c\x6c\x6f"; // Hello in binary
$hexData= bin2hex($binaryData);
echo"Hexadecimal: $hexData";
?>
Output:
Hexadecimal: 48656c6c6f
This function decodes a hexadecimally encoded binary string.
Example:
<?php
$hexData= "48656c6c6f"; // Hexadecimal representation of "Hello"
$binaryData= hex2bin($hexData);
echo"Decoded: $binaryData";
?>
Output:
Decoded: Hello
This function returns the ASCII value of the first character of a string.
Example:
<?php
$text= "A";
$asciiValue= ord($text);
echo"ASCII Value: $asciiValue";
?>
Output:
ASCII Value: 65
This function tokenizes a string using a specified delimiter.
Example:
<?php
$text= "apple,banana,orange";
$token= strtok($text, ",");
while($token!== false) {
echo"Token: $token
";
$token= strtok(",");
}
?>
Output:
Token: apple
Token: banana
Token: orange
This function returns the string value of a variable.
Example:
<?php
$number= 42;
$stringValue= strval($number);
echo"String Value: $stringValue";
?>
Output:
String Value: 42
This function performs a case-insensitive string comparison of the first n characters.
Example:
<?php
$text1= "apple";
$text2= "Apples";
$result= strncasecmp($text1, $text2, 4);
echo"Comparison Result: $result";
?>
Output:
Comparison Result: 0
This function finds the first occurrence of a character in a string and returns the part of the string from that occurrence to the end.
Example:
<?php
$text= "This is a test string.";
$substring= strchr($text, "test");
echo"Found: $substring";
?>
Output:
Found: test string.
This function finds the last occurrence of a substring in a string.
Example:
<?php
$text= "This is a test string. This is another test.";
$position= strrpos($text, "test");
echo"Last Occurrence at position: $position";
?>
Output:
Last Occurrence at position: 39
This is the case-insensitive version of strrpos().
Example:
<?php
$text= "This is a test string. This is another test.";
$position= strripos($text, "TEST");
echo"Last Occurrence (Case-Insensitive) at position: $position";
?>
Output:
Last Occurrence (Case-Insensitive) at position: 39
This function compares two substrings in a case-sensitive manner.
Example:
<?php
$text1= "apple";
$text2= "apples";
$result= substr_compare($text1, $text2, 0, 5);
echo"Comparison Result: $result";
?>
Output:
Comparison Result: 0
The echo() function is used to output one or more strings or variables to the web page.
Example:
<?php
$name= "John";
$age= 30;
echo"Hello, my name is $name and I am $age years old.";
?>
Output:
Hello, my name is John and I am 30 years old.
This function is used to output a single string or variable to the web page.
Example:
<?php
$name= "Alice";
$age= 25;
print("Hello, my name is $name and I am $age years old.");
?>
Output:
Hello, my name is Alice and I am 25 years old.
These functions are the backbone of PHP development, enabling you to build powerful websites and applications with precision and efficiency. Keep this list of functions handy so you can quickly reference them as needed and continue to improve your PHP coding skills.