List of PHP String functions (Hypertext Preprocessor)

lakshmi , Credit to  volkotech-solutions Mar 14

This blog offers an explanation of the most useful PHP (Hypertext Preprocessor) string functions, along with reader a better understanding and examples.

The processing of strings in PHP, a popular programming language for web development, is one of its key aspects. A wide range of string-related actions, including concatenation, searching, replacing, and formatting, is supported by a robust collection of built-in functions in PHP. These functions enable developers to easily and quickly perform a variety of string operations, saving time and effort during the development process.

List of PHP String functions with examples:

String function Name

Description 

Example

output

addcslashes()

Adding slashes to certain characters in a string using this PHP function.

Syntax: addcslashes(string $string, string $charlist): string

$string = "Hello, world!";
$charlist = "Hweo";
$result = addcslashes($string, $charlist);
echo $result;

// add a slash before H, w, e, and o

\H\ell\o, \w\orld!

addslashes()

Adding slashes to the specified character in a string using this PHP function.

Syntax: addslashes(string $string): string

$string = "This is a 'test' string.";
$result = addslashes($string);
echo $result;

// add slashes before single quotes.

This is a \'test\' string.

explode()

Divides a string into an array of substrings based on a given delimiter.

Syntax: explode(string $delimiter, string $string, int $limit = PHP_INT_MAX): array

$string = "apple,banana,orange";
$array = explode(",", $string);
print_r($array);


echo $array[1];

// Split a string into an array of substrings

Array ( [0] => apple [1] => banana [2] => orange )

// Access the element of the array

banana

fprintf()

It allows you to write formatted data to a file or output stream.

Syntax: fprintf($handle, $format, $arg1, $arg2, ...);

$handle = fopen("output.txt", "w");

$name = "Alice";

$age = 30;

fprintf($handle, "My name is %s and I am %d years old.", $name, $age);

fclose($handle);

// string in output.txt file

My name is Alice and I am 30 years old.

html_entity_decode()

It is used to convert HTML entities back to their appropriate characters.

Syntax: html_entity_decode($string, $flags, $encoding);

$string1 = "This is a &quot<test>&quot.";

$string2 = htmlentities($string1);

$decoded = html_entity_decode($string2);

echo $decoded;

// Display the decoded string

This is a "<test>".

htmlentities()

It is used to convert characters to their corresponding HTML entities.

Syntax: htmlentities($string, $flags, $encoding, $double_encode);

$string = "<test>";

$encoded = htmlentities($string);

echo $encoded; 

// Display the encoded string

&lt;test&gt;

implode()

It is used to combine an array's items into a string.

Syntax: implode($delimiter, $array);

$array = array('apple', 'banana', 'cherry');

$string = implode(', ', $array);

 echo $string;

// Display the resulting in string

apple, banana, cherry

lcfirst()

It converts the first character of a string to a lowercase.

Syntax:lcfirst($string);

$string = "Hello, World!";

$string = lcfirst($string);

echo $string;

// Display the resulting string

hello, World!

ltrim()

It removes whitespace or other specified characters from the beginning (left side) of a string.

Syntax: ltrim($string, $characters);

$string = "      Hello, World!";

$string1 = ltrim($string);

echo $string;

// Display the resulting string

Hello, World!

md5_file()

It is used to calculate the MD5 hash of a file.

Syntax: md5_file($filename, $raw_output = false);

$filename = "example.txt";

$hash = md5_file($filename);

echo $hash;

// Display the resulting hash

e9d71f5ee7c92d6dc9e92ffdad17b8bd

md5()

It is used to calculate the MD5 hash of a string.

Syntax: md5($string, $raw_output = false);

$string = "Hello, World!";

$hash = md5($string);

echo $hash;

// Display the resulting hash

ed076287532e86365e841e92bfc50d8c

rtrim()

It removes any whitespace or specified characters from the end of a string.

Syntax: rtrim($string, $charlist = " \t\n\r\0\x0B");

$string = " Hello, World!       \n";

$trimmed_string = rtrim($string);

echo $trimmed_string;

// Display the resulting string

Hello, World!

similar_text()

It calculates the similarity between two strings as a percentage.

Syntax: similar_text($string1, $string2, &$percent);

$string1 = "Hello, World!";

$string2 = "Hello, everyone!";

similar_text($string1, $string2, $percent);

echo "The two strings are $percent% similar.";

// Display the similarity percentage

The two strings are 62.068965517241% similar.

sprintf()

It allows to format a string using placeholders.

Syntax: sprintf($format, $arg1, $arg2, ...);

$name = "Alice";

$age = 25;

$string = sprintf("Hello, my name is %s and I am %d years old.", $name, $age);

echo $string;

// Display the formatted string

"Hello, my name is Alice and I am 25 years old."

sscanf()

It reads data from a string according to a specified format.

Syntax: sscanf($string, $format, &$var1, &$var2, ...);

$auth = "24\tLewis Carroll";

$n = sscanf($auth, "%d\t%s %s", $age, $firstname, $lastname);

echo "Age: $age<br>";

echo "First Name: $firstname";

echo "Last Name: $lastname";

// Display the extracted data

Age: 24
First Name: Lewis
Last Name: Carroll

str_contains()

It checks if a string contains a specific substring or not. It returns true if the substring is found in the string, and false otherwise.

Syntax: str_contains($haystack, $needle);

$string = "Hello, World!";

$substring = "World";

if (str_contains($string, $substring)) {

echo "The string '$string' contains the substring '$substring'";

} else {

echo "The string '$string' does not contain the substring '$substring'";

}

The string 'Hello, World!' contains the substring 'World'

str_ends_with()

It checks if a string ends with a specific suffix or not. It returns true if the string ends with the suffix, and false otherwise.

Syntax: str_ends_with($string, $suffix);

$string = "Hello, World!";

$suffix = "World!";

if (str_ends_with($string, $suffix)) {

echo "The string '$string' ends with the suffix '$suffix'";

} else {

echo "The string '$string' does not end with the suffix '$suffix'";

}

The string 'Hello, World!' ends with the suffix 'World!'

str_ireplace()

It is a function in PHP that performs a case-insensitive search.

Syntax: str_ireplace($search, $replace, $subject, &$count = null);

$string = "Hello World!";

$search = "world";

$replace = "PHP";

$result = str_ireplace($search, $replace, $string);

echo $result;

Hello PHP!

str_pad()

It is used to pad a string to a specified length with another string.

Syntax: str_pad($input_string, $pad_length, $pad_string = " ", $pad_type = STR_PAD_RIGHT);

$string = "Hello";

$pad_length = 10;

$pad_string = "-";

$pad_type = STR_PAD_BOTH;

$result = str_pad($string, $pad_length, $pad_string, $pad_type);

echo $result;

--Hello---

str_repeat()

It is used to repeat a string a specified number of times.

Syntax: str_repeat($input_string, $multiplier);

$string = "Hello";

$multiplier = 3;

$result = str_repeat($string, $multiplier);

echo $result;

HelloHelloHello

str_replace()

It is used to replace all occurrences of a search string with a replacement string in a given string.

Syntax: syntax: str_replace(search, replace, subject, count);

$subject = "The quick brown fox jumps over the lazy dog.";

$search = "fox";

$replace = "cat";

$result = str_replace($search, $replace, $subject);

echo $result;

The quick brown cat jumps over the lazy dog.

str_shuffle()

It is used to randomly shuffle the characters in a string.

Syntax: str_shuffle($string);

$string = 'abcdefgh12345&*^%$';

$string_shuffled = str_shuffle($string);

echo $string_shuffled;

4a%2heb31*^f5&dg$c

str_split()

It is used to split a string into an array of substrings, each containing a specified number of characters.

Syntax: str_split($string, $split_length);

$string = "Hello, World!";

$result = str_split($string);

print_r($result);

echo $result[7];

//split a string into an array of substrings.

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => , [6] => [7] => W [8] => o [9] => r [10] => l [11] => d [12] => ! )

// Access the element of the array

W

str_starts_with()

It is used to check if a string starts with a specified substring.

Syntax: str_starts_with($string, $prefix);

$string = "Hello, World!";

$prefix1 = "Hello";

$prefix2 = "world";

$result1 = str_starts_with($string, $prefix1)

$result2 = str_starts_with($string, $prefix2); 

echo "Result 1: " . ($result1 ? "true" : "false") . "\n";

echo "Result 2: " . ($result2 ? "true" : "false") . "\n";

Result 1: true

Result 2: false

str_word_count()

It is used to count the number of words in a string.

Syntax: str_word_count($string, $format = 0, $charlist = null);

$string = "This is a test string";

$word_count = str_word_count($string); echo "Word count: " . $word_count . "\n";

Word count: 5

strcmp()

It is used to compare two strings. It returns an integer value that indicates the result of the comparison.

Syntax: strcmp(string $str1, string $str2): int

$string1 = "apple";

$string2 = "banana";

$result = strcmp($string1, $string2);

if ($result == 0) {

echo "$string1 and $string2 are equal";

} elseif ($result < 0) {

echo "$string1 comes before $string2";

} else {

echo "$string1 comes after $string2";

}

apple comes before banana
strcoll()

It is used to compare two strings using the current locale.

Syntax: strcoll(string $str1, string $str2): int

$string1 = "cafe";

$string2 = "chateau";

$result = strcoll($string1, $string2);

if ($result == 0) {

echo "$string1 and $string2 are equal";

} elseif ($result < 0) {

echo "$string1 comes before $string2";

} else {

echo "$string1 comes after $string2";

}

cafe comes before chateau
strcspn()

It calculates the first segment of a string's length from a predetermined set of characters that contains no characters.

Syntax: strcspn(string $str, string $charlist [, int $start [, int $length ]]): int

$string = "hello world";

$chars = "aeiou";

$result = strcspn($string, $chars);

echo "The length of the initial segment of '$string' that contains none of the characters in '$chars' is: $result";

The length of the initial segment of 'hello world' that contains none of the characters in 'aeiou' is: 1
strip_tags()

It removes HTML and PHP tags from a string and returns plain text content.

Syntax: strip_tags(string $str [, string $allowable_tags ]): string

$str = '<p>Hello <b>world</b>!</p>';

$clean_str = strip_tags($str);

echo $clean_str; 

 

$str = '<p>Hello <b>world</b>!</p>';

$allowed_tags = '<b>';

$clean_str = strip_tags($str, $allowed_tags);

echo $clean_str;

Hello world!

 

 

 

 


Hello world!

stripcslashes()

It removes slashes from a string.

Syntax: stripcslashes(string $str): string

$str = "This is an example of a string with \'slashes\'";

$clean_str = stripcslashes($str);

echo $clean_str;

This is an example of a string with 'slashes'
stripos()

It searches the first position in a string where a case-insensitive substring appears.

Syntax: stripos(string $haystack, string $needle [, int $offset = 0 ]): int|false

$str = 'The quick brown fox jumps over the lazy dog';

$pos = stripos($str, 'brown');

if ($pos !== false) {

echo "Found 'brown' at position $pos";

} else {

echo "'brown' not found";

}

Found 'brown' at position 10
stripslashes()

It removes slashes from a string.

Syntax: stripslashes(string $str): string

$string_with_backslashes = "This is an example string with \'backslashes\'.";

$string_without_backslashes = stripslashes($string_with_backslashes);

echo $string_without_backslashes;

This is an example string with 'backslashes'.
stristr()

Case-insensitively, it searches for a substring's initial appearance within a string.

Syntax: stristr(string $haystack, mixed $needle [, bool $before_needle = false ]): string|false

$str = 'The quick brown fox jumps over the lazy dog';

$match = stristr($str, 'BROWN');

if ($match !== false) {

echo "Found '$match'";

} else {

echo "'BROWN' not found";

}

Found 'brown fox jumps over the lazy dog'
strlen()

It returns the length of a string.

Syntax: strlen(string $string): int

$str = "Hello, world!";

$len = strlen($str);

echo $len;

13
strnatcasecmp()

It compares two strings using a "natural order" algorithm that is case-insensitive.

Syntax: strnatcasecmp(string $str1, string $str2): int

$str1 = "file1.txt";

$str2 = "File10.txt";

$result = strnatcasecmp($str1, $str2);

if ($result < 0) {

echo "$str1 comes before $str2";

} elseif ($result == 0) {

echo "$str1 is equal to $str2 ";

} else {

echo "$str1 comes after $str2 ";

}

file1.txt comes before File10.txt
strnatcmp()

It compares two strings using a "natural order" algorithm that is case-sensitive.

Syntax: strnatcmp(string $str1, string $str2): int

$str1 = "file1.txt";

$str2 = "File10.txt";

$result1 = strnatcmp($str1, $str2);

if ($result1 < 0) {

echo "$str1 comes before $str2 ";

} elseif ($result1 == 0) {

echo "$str1 is equal to $str2 ";

} else {

echo "$str1 comes after $str2 ";

}

file1.txt comes after File10.txt 
strncasecmp()

It compares two strings, ignoring case, up to a specified length.

Syntax: strncasecmp( string $str1 , string $str2 , int $length )

$str1 = "Hello World";

$str2 = "hello world";

$result = strncasecmp($str1, $str2, 5);

if ($result < 0) {

echo "$str1 is less than $str2\n";

} elseif ($result == 0) {

echo "$str1 is equal to $str2\n";

} else {

echo "$str1 is greater than $str2\n";

}

Hello World is equal to hello world
strncmp()

It compares two strings up to a specified length.

Syntax: strncmp( string $str1 , string $str2 , int $length )

$str1 = "Hello World";

$str2 = "Hello PHP";

$result = strncmp($str1, $str2, 5);

if ($result < 0) {

echo "$str1 is less than $str2\n";

} elseif ($result == 0) {

echo "$str1 is equal to $str2\n";

} else {

echo "$str1 is greater than $str2\n";

}

Hello World is equal to Hello PHP
strpbrk()

It searches a string for the first occurrence of any character from a specified set of characters.

Syntax: strpbrk( string $haystack , string $char_list )

$str = "Hello World";

$chars = "oe";

$result = strpbrk($str, $chars);

if ($result) {

echo "Found the first occurrence of any of the characters $chars in $str: $result\n";

} else {

echo "None of the characters $chars were found in $str\n";

}

Found the first occurrence of any of the characters oe in Hello World: ello World
strpos()

It searches for the first occurrence of a string inside another string and returns the position of its occurrence.

Syntax: strpos( string $haystack , mixed $needle [, int $offset = 0 ] )

$str = "Hello World";

$pos = strpos($str, "World");

if ($pos !== false) {

echo "Found 'World' at position $pos in '$str'\n";

} else {

echo "Did not find 'World' in '$str'\n";

}

Found 'World' at position 6 in 'Hello World'
strrchr()

It searches a string for the last occurrence of a specified character.

Syntax: strrchr( string $haystack , mixed $needle )

$str = "Hello World";

$substr = strrchr($str, "o");

if ($substr) {

echo "Found last occurrence of 'o' in '$str': '$substr'\n";

} else {

echo "Did not find 'o' in '$str'\n";

}

Found last occurrence of 'o' in 'Hello World': 'orld'
 
strrev()

It reverses a given string.

Syntax: strrev( string $string )

$str = "Hello World";

$reversed = strrev($str);

echo "Original string: $str\nReversed string: $reversed\n";

Original string: Hello World

Reversed string: dlroW olleH

strripos()

It searches a string for the last occurrence of a specified substring (case-insensitive).

Syntax: strripos( string $haystack , string $needle [, int $offset = 0 ] )

$str = "Hello World";

$pos = strripos($str, "o");

if ($pos !== false) {

echo "Found last occurrence of 'o' (case-insensitive) in '$str' at position $pos\n";

} else {

echo "Did not find 'o' (case-insensitive) in '$str'\n";

}

Found the last occurrence of 'o' (case-insensitive) in 'Hello World' at position 7
strrpos()

It searches a string for the last occurrence of a specified substring and returns its position in the string.

Syntax: strrpos ( string $haystack , string $needle [, int $offset = 0 ] )

$str = "Hello World";

$pos = strrpos($str, "o");

if ($pos !== false) {

echo "Found last occurrence of 'o' in '$str' at position $pos\n";

} else {

echo "Did not find 'o' in '$str'\n";

}

Found the last occurrence of 'o' in 'Hello World' at position 7
strspn()

It calculates the length of the initial substring of a string that consists entirely of characters from a specified mask.

Syntax: strspn ( string $str , string $mask [, int $start = 0 [, int $length ]] )

$str = "Hello World";

$mask = "HeloWrd";

$len = strspn($str, $mask);

echo "The length of the initial substring of '$str' that contains only characters from '$mask' is $len\n";

The length of the initial substring of 'Hello World' that contains only characters from 'HeloWrd' is 5
strstr()

It searches for the first occurrence of a substring within a string.

Syntax: strstr ( string $haystack , mixed $needle [, bool $before_needle = false ] )

$str = "Hello World";

$sub = "World";

$result = strstr($str, $sub);

if ($result !== false) {

echo "Found '$sub' in '$str': '$result'\n";

} else {

echo "Did not find '$sub' in '$str'\n";

}

Found 'World' in 'Hello World': 'Worl
strtok()

It splits a string into smaller parts, or "tokens," based on a delimiter character.

Syntax: strtok ( string $str , string $delimiters )

$str = "The quick brown fox jumps over the lazy dog";

$delimiters = " ";

$token = strtok($str, $delimiters);

while ($token !== false) {

echo $token . "<br>";

$token = strtok($delimiters);

}

The
quick
brown
fox
jumps
over
the
lazy
dog

strtolower()

It converts a given string to all lowercase characters.

Syntax: strtolower ( string $string )

$string = "This is a STRING with SOME UPPER CASE CHARACTERS";

echo strtolower($string);

this is a string with some upper case characters
strtoupper()

It converts a given string to all uppercase characters.

Syntax: strtoupper ( string $string )

$string = "This is a string with some lowercase characters"; echo strtoupper($string);

THIS IS A STRING WITH SOME LOWERCASE CHARACTERS

strtr()

It performs a string translation or replacement based on a given translation table.

Syntax: strtr ( string $string , array $translation_table )

$string = "Hello, world!";

$translation_table = array( 'H' => 'J', 'W' => 'V', 'o' => '0' );

echo strtr($string, $translation_table);

Jell0, w0rld!
substr_compare()

It compares two substrings of a given string.

Syntax: substr_compare ( string $main_str , string $str , int $offset [, int $length [, bool $case_insensitivity = false ]] )

$main_str = "Hello, world!";

$str = "world";

$offset = 7;

$length = 5;

$result = substr_compare($main_str, $str, $offset, $length, true);

if ($result === 0) {

echo "The two substrings are equal.\n";

} else {

echo "The two substrings are not equal.\n";

}

The two substrings are equal.
substr_count()

It counts the number of occurrences of a substring within a given string.

Syntax: substr_count ( string $haystack , string $needle [, int $offset = 0 [, int $length ]] )

$haystack = "The quick brown fox jumps over the lazy dog.";

$needle = "o";

$count = substr_count($haystack, $needle);

echo "The substring '$needle' was found $count times in the input string.\n";

The substring 'o' was found 4 times in the input string.
substr_replace()

It replaces a portion of a string with another string.

Syntax: substr_replace ( string $string , string $replacement , mixed $start [, mixed $length ] )

$string = "The quick brown fox jumps over the lazy dog.";

$replacement = "red";

$start = 10;

$length = 5;

$result = substr_replace($string, $replacement, $start, $length);

echo $result;

The quick red fox jumps over the lazy dog.
substr()

It returns a portion of a string.

Syntax: substr ( string $string , int $start [, int $length ] )

$string = "Hello world!";

$sub = substr($string, 6, 5);

echo $sub;

world
trim()

It removes whitespace or other specified characters from the beginning and end of a string. 

Syntax: trim ( string $string [, string $character_mask = " \t\n\r\0\x0B" ] )

$string = "   Hello world!   ";

$trimmed = trim($string);

echo $trimmed;

Hello world!
ucfirst()

It converts the first character of a string to uppercase.

Syntax: ucfirst ( string $str )

$string = "hello world";

$capitalized = ucfirst($string);

echo $capitalized;

Hello world
ucwords()

It capitalizes the first character of each word in a string.

Syntax: ucwords ( string $str )

$string = "hello world";

$capitalized = ucwords($string);

echo $capitalized;

Hello World
wordwrap()

It wraps a string to a specified number of characters per line.

Syntax: wordwrap ( string $str , int $width [, string $break = "\n" [, bool $cut = false ]] )

$text = "Lorem ipsum dolor sit amet, consectetur adipiscing elit. Aenean ut ante euismod, cursus mauris id, feugiat augue. Sed faucibus enim in elit tristique, non bibendum eros ultricies. Proin facilisis eleifend sapien, at euismod nulla consequat a.";

$wrapped_text = wordwrap($text, 40, "<br>\n");

echo $wrapped_text;

Lorem ipsum dolor sit amet, consectetur
adipiscing elit. Aenean ut ante euismod,
cursus mauris id, feugiat augue. Sed
faucibus enim in elit tristique, non
bibendum eros ultricies. Proin facilisis
eleifend sapien, at euismod nulla
consequat a.

 

Comments