String Function in PHP
A string is a collection of characters. String is one of the data types supported by PHP. The string variables can contain alphanumeric characters. Strings are created when;
- You declare variable and assign string characters to it
- You can directly use PHP Strings with echo statement.
- PHP String functions are language construct, it helps capture words.
- Learning how strings work in PHP and how to manipulate them will make you a very effective and productive developer.
Types of Strings
Quoting string constants in PHP can be done using single quotes ('), double quotes ("), and the here document (heredoc) format. Each of these methods has its own characteristics and use cases. Here are examples :
1. Variable Interpolation
Variable interpolation is a feature in programming languages that allows you to insert the values of variables directly into strings. This makes it easy to create dynamic strings by embedding variable values within them.
In PHP, variable interpolation is commonly used in strings enclosed in double quotes (" "). Here's how variable interpolation works in PHP.
Using Variable Interpolation in PHP
In PHP, you can include variable values within double-quoted strings. Variables are denoted by a dollar sign ($) followed by the variable name, and they will be replaced with their actual values when the string is evaluated.
<?php
$name = "Harry";
$age = 30;
// Variable interpolation in a double-quoted string
$message = "My name is $name, and I am $age years old.";
echo $message;
?>In this example, the variables $name and $age are interpolated into the string, and the resulting string stored in the $message variable will be "My name is John, and I am 30 years old."
2. Strings Using Single Quotes (' ')
Enclosing a string in single quotes is the simplest way to create a string constant. The string will be treated literally, and variables or escape sequences within it won't be interpreted.
Useful for simple strings without variables or special characters.
<?php
$variable = 'world';
echo 'Hello, $variable';
?>Output: Hello $name
If the single quote is part of the string value, it can be escaped using the backslash. The code below illustrates how to escape a single quote.
3. Strings Using Double Quotes
Enclosing a string in double quotes allows for variable interpolation, escape sequences, and special characters. Variables enclosed in double quotes will be replaced with their values.
Useful when you need to include variables or special characters within the string.
<?php
$name='Alicia';
echo "$name is friends with kalinda";
?>Output: Alicia is friends with kalinda
The above example creates a simple string with the value of Alicia. The variable name is then used in the string created using double quotes and its value is interpolated at run time.
3. Here Document (Heredoc)
Heredoc is a way to define multiline strings without the need for escaping quotes or special characters. It's especially useful when working with large blocks of text.
Heredoc syntax begins with <<<, followed by a delimiter (often EOT, but you can use any identifier), and ends with the same delimiter.
<?php
$variable = 'world';
$message = <<< 'EOT'
Hello, $variable!
This is a multiline string.
EOT;
echo $message;
?>Output: Hello, World This is multiline string.
In this example, <<<EOT marks the start of the heredoc string, and EOT; marks the end. Variables are interpolated, and line breaks and special characters are preserved.
CONCATENATION OF TWO STRINGS
There are two string operators. The first is the concatenation operator (‘.‘), which returns the concatenation of its right and left arguments.
The second is the concatenating assignment operator (‘.=‘), which appends the argument on the right side to the argument on the left side.
<?php
$fname = 'John';
$lname = 'Carter!';
$c = $fname." ".$lname;
echo " $c \n";
// Output: John Carter!
?>String Functions in PHP
PHP have lots of predefined function which is used to perform operation with string some functions are.
strlen()
strlen() function returns the length of a string.
<?php
echo strlen("Hello world!");
// Output: 12
?>str_word_count()
str_word_count() function is used to count numbers of words in given string.
<?php
echo str_word_count("Hello world!");
// Output: 2
?>strrev()
strrev() function is used to revers any string.
<?php
echo strrev("Hello world!");
// Output: !dlrow olleH
?>strtolower()
strtolower() function is used to convert uppercase latter into lowercase latter.
<?php
$str="Hello friends i am HITESH";
$str=strtolower($str);
echo $str;
// Output: hello friends i am hitesh
?>
strtoupper()
PHP strtoupper() function is used to convert lowercase latter into uppercase latter.
<?php
$str="Hello friends i AM Hitesh";
$str=strtoupper($str);
echo $str;
// Output: HELLO FRIENDS I AM HITESH
?>ucwords()
ucwords() function is used to convert first letter of every word into upper case.
<?php
$str="hello friends i am hitesh";
$str=ucwords($str);
echo $str;
// Output: Hello Friends I Am Hitesh
?>Comparing Strings
In PHP, we can compare strings in various ways, depending on our specific requirements. Here are some two common methods for comparing strings in PHP.
1. Exact Comparison
The === operator checks for both the content and the data type to be identical. This means that not only should the strings have the same characters but they should also be of the same data type (string).
<?php
$string1 = "Hello";
$string2 = "Hello";
if ($string1 === $string2) {
echo "Strings are exactly equal.";
} else {
echo "Strings are not exactly equal.";
}
// Output : Strings are exactly equal.
?>In Exact Comparison, we can compare strings in various ways, depending on our specific requirements. Here are some common methods for comparing strings.
2. Equality Comparison (==)
We can use the double equals (==) operator to compare if two strings are equal in terms of their content. This comparison is case-insensitive.
<?php
$string1 = "Hello";
$string2 = "hello";
if ($string1 == $string2) {
echo "Strings are equal.";
} else {
echo "Strings are not equal.";
}
// Output : Strings are not equal.
?>3. Case-Insensitive Comparison
To compare strings while ignoring the case (make it case-insensitive), you can use functions like strcasecmp() or stricmp()
<?php
$string1 = "Hello";
$string2 = "hello";
if (strcasecmp($string1, $string2) == 0) {
echo "Strings are equal (case-insensitive).";
} else {
echo "Strings are not equal (case-insensitive).";
}
// Output : Strings are equal (case-insensitive).
?>4. String Comparison Functions
PHP provides several functions for comparing strings, including strcmp() and strnatcmp(). These functions return 0 if the strings are equal and a positive or negative number depending on their order:
<?php
$string1 = "apple";
$string2 = "banana";
$result = strcmp($string1, $string2);
if ($result == 0) {
echo "Strings are equal.";
} elseif ($result < 0) {
echo "String 1 is less than String 2.";
} else {
echo "String 1 is greater than String 2.";
}
// Output : String 1 is less than String 2.
?>5. String Length Comparison
We can also compare strings based on their length using the strlen() function or by comparing their length directly.
<?php
$string1 = "Hello";
$string2 = "Hello, world!";
if (strlen($string1) == strlen($string2)) {
echo "Strings have the same length.";
} else {
echo "Strings have different lengths.";
}
// Output : Strings have different lengths.
?>Appropriate Equality Comparison
PHP provides several functions that allow us to test whether two strings are approximately equal. The Functions soundex(), metaphone(), similar_text() and levenshtein() are useful for comparing strings based on their phonetic or similarity characteristics.
Here's an overview of these functions.
1. soundex()
- The soundex() function calculates a phonetic representation of a string.
- It's often used to compare words that sound similar.
- It returns a four-character code representing the string's phonetic sound.
- We can use soundex() to find words that have similar pronunciations.
<?php
$word1 = "hello";
$word2 = "helo";
if (soundex($word1) === soundex($word2)) {
echo "Words sound similar.";
} else {
echo "Words do not sound similar.";
}
// Output : Words sound similar.
?>2. metaphone()
- The metaphone() function provides another way to create a phonetic representation of a string.
- It returns a metaphone key, which is a more modern and flexible alternative to soundex.
- metaphone() is used to find similar-sounding words.
<?php
$word1 = "write";
$word2 = "right";
if (metaphone($word1) === metaphone($word2)) {
echo "Words sound similar.";
} else {
echo "Words do not sound similar.";
}
// Output : Words do not sound similar
?>3. similar_text()
- The similar_text() function calculates the similarity between two strings as a percentage.
- It returns the number of matching characters between the two strings.
- This function is useful for finding the similarity between two strings, regardless of phonetics.
<?php
$string1 = "programming";
$string2 = "programmer";
similar_text($string1, $string2, $percentage);
echo "Similarity: $percentage%";
// Output : Similarity : 76.190476190476 %
?>4. levenshtein()
- The levenshtein() function calculates the Levenshtein distance between two strings.
- It measures the number of single-character edits (insertions, deletions, substitutions) required to change one string into another.
- A smaller Levenshtein distance indicates greater similarity.
<?php
$string1 = "kitten";
$string2 = "sitting";
$distance = levenshtein($string1, $string2);
echo "Levenshtein distance: $distance";
// Output : Levenshtein distance : 3
?>Cleaning Strings
Often, the strings we get from files or users need to be cleaned up before we can use them. Two common problems with raw data are the presence of extraneous whitespace and incorrect capitalization (uppercase versus lowercase).
1. Removing Whitespace
Cleaning and removing whitespace from strings is a common task in programming, and it can be done in various ways in PHP. Here are some points on how to remove whitespace from strings.
Using trim(), ltrim(), and rtrim()
- The trim() function removes whitespace (spaces, tabs, and newline characters) from the beginning and end of a string.
- ltrim() removes whitespace from the beginning (left) of a string, while rtrim() removes whitespace from the end (right).
- These functions are helpful when you want to clean user input or remove unnecessary spaces.
<?php
$string = " Hello, World! ";
$trimmed = trim($string);
echo $trimmed; // Output: "Hello, World!"
// Output: "Hello, World!"
?>2. Changing Case
PHP has several functions for changing the case of strings: strtolower() and strtoupper() operate on entire strings, ucfirst() operates only on the first character of the string, and ucwords() operates on the first character of each word in the string.
Each function takes a string to operate on as an argument and returns a copy of that string, appropriately changed.
<?php
$string1 = "FRED flintstone";
$string2 = "barney rubble";
print(strtolower($string1));
print(strtoupper($string1));
print(ucfirst($string2));
print(ucwords($string2));
?> Output:
fred flintstone
FRED FLINTSTONE
Barney rubble
Barney RubbleIf we’ve got a mixed-case string that you want to convert to “title case,” where the first letter of each word is in uppercase and the rest of the letters are in lowercase (and you are not sure what case the string is in to begin with), use a combination of strtolower() and ucwords(): print(ucwords(strtolower($string1))); Fred Flintstone