Method 1: Using the strpos()
Function to Check if a PHP String Contains a Substring
The strpos()
function is a built-in PHP function that lets you check if a string contains a substring. It returns the index of the first occurrence of the substring in the string, or false
if the substring is not found.
How the strpos()
Function Works
The strpos()
function takes two parameters:
$haystack
: The string to search in.$needle
: The substring to search for.
It returns an integer that represents the index of the first occurrence of the needle in the haystack, or false
if the needle is not found.
Note that strpos()
does a case-sensitive search. This means that it considers uppercase and lowercase letters when searching for the substring.
Here's an example of how to use strpos()
to check if a string contains a word:
$word = "fox";
$mystring = "The quick brown fox jumps over the lazy dog";
// Test if string contains the word
if (strpos($mystring, $word) !== false) {
echo "Word Found!";
} else {
echo "Word Not Found!";
}
In this code:
- We set the
$word
variable as the substring we want to search for, which is "fox". - We also have the
$mystring
variable that has the sentence we want to search for the word in. - We use the
strpos()
function to check if$mystring
contains$word
.- If the word is found,
strpos()
returns the index of its first occurrence. - If the word is not found,
strpos()
returnsfalse
.
- If the word is found,
- The condition
strpos($mystring, $word) !== false
checks if the returned value is notfalse
.- If the word is found, the condition is true, and the code in the if block runs, printing "Word Found!".
- If the word is not found, the else block runs, printing "Word Not Found!".
Example
Let's say you have a form on your website where users can enter their email addresses. You want to check the email addresses to make sure they are from a domain, such as "example.com". Here's how you can use strpos()
to check if the email address contains the domain:
$email = "user@example.com";
$domain = "example.com";
if (strpos($email, $domain) !== false) {
echo "Valid email domain!";
} else {
echo "Invalid email domain!";
}
In this example, we check if the $email
string contains the $domain
substring. If it does, we consider the email address valid and print "Valid email domain!". If it doesn't, we print "Invalid email domain!".
Differences Between strpos()
and stripos()
Functions
PHP also has the stripos()
function, which is like strpos()
but does a case-insensitive search. This means that stripos()
doesn't consider uppercase and lowercase letters when searching for the substring.
You would use strpos()
when you need to do a case-sensitive search and want to match the exact case of the substring. You would use stripos()
when the case of the substring doesn't matter, and you want to find the substring no matter its case.
Here's an example to show the difference:
$word = "Fox";
$mystring = "The quick brown fox jumps over the lazy dog";
if (strpos($mystring, $word) !== false) {
echo "Word Found using strpos()!";
} else {
echo "Word Not Found using strpos()!";
}
if (stripos($mystring, $word) !== false) {
echo "Word Found using stripos()!";
} else {
echo "Word Not Found using stripos()!";
}
In this case:
strpos()
would return "Word Not Found!" because it does a case-sensitive search and the substring "Fox" (with an uppercase "F") doesn't exist in the string.stripos()
would return "Word Found!" because it does a case-insensitive search and finds the substring "fox" (with a lowercase "f") in the string.
Comparing strpos()
with Other String Searching Functions
PHP has other functions for searching in strings, such as strstr()
, stristr()
, strrchr()
, and strpbrk()
. Here's a comparison of these functions:
Function | Description | Returns |
---|---|---|
strpos() |
Finds the position of the first occurrence of a substring | Index of the first occurrence or false |
strstr() |
Finds the first occurrence of a substring | Substring from the first occurrence or false |
stristr() |
Case-insensitive version of strstr() |
Substring from the first occurrence or false |
strrchr() |
Finds the last occurrence of a character | Substring from the last occurrence or false |
strpbrk() |
Searches a string for any of a set of characters | Substring from the first occurrence or false |
Example
$mystring = "The quick brown fox jumps over the lazy dog";
// Using strpos()
$position = strpos($mystring, "fox");
echo "Position of 'fox' using strpos(): " . $position . "\n";
// Using strstr()
$substring = strstr($mystring, "brown");
echo "Substring from 'brown' using strstr(): " . $substring . "\n";
// Using stristr()
$substring = stristr($mystring, "JUMPS");
echo "Substring from 'JUMPS' using stristr(): " . $substring . "\n";
// Using strrchr()
$substring = strrchr($mystring, "o");
echo "Substring from the last 'o' using strrchr(): " . $substring . "\n";
// Using strpbrk()
$substring = strpbrk($mystring, "aeiou");
echo "Substring from the first vowel using strpbrk(): " . $substring . "\n";
Output:
Position of 'fox' using strpos(): 16
Substring from 'brown' using strstr(): brown fox jumps over the lazy dog
Substring from 'JUMPS' using stristr(): jumps over the lazy dog
Substring from the last 'o' using strrchr(): og
Substring from the first vowel using strpbrk(): e quick brown fox jumps over the lazy dog
Method 2: Check if a String Contains a Word Using str_contains()
in PHP 8
PHP 8 added a new function called str_contains()
that makes it easier to check if a string contains a substring. This function simplifies searching for a specific word within a string, improving code readability and performance.
str_contains()
Function
The str_contains()
function is new in PHP 8 that lets you check if a string contains a substring. It returns a boolean value showing if the substring is found within the string.
This function provides a simpler way to do this common task compared to using strpos()
or stripos()
, which need more checks for the returned value.
Syntax and Usage of str_contains()
The str_contains()
function has this syntax:
str_contains(string $haystack, string $needle): bool
$haystack
: The string to search in.$needle
: The substring to search for.
The function returns true
if the $needle
is found within the $haystack
, and false
if not.
Here's an example of how to use str_contains()
to check if a string contains a specific word:
$text = "The quick brown fox jumps over the lazy dog";
$word = "fox";
if (str_contains($text, $word)) {
echo "The word '$word' is found in the text.";
} else {
echo "The word '$word' is not found in the text.";
}
In this example, str_contains()
checks if the string $text
contains the word $word
. Since the word "fox" is in the text, the function returns true
, and the message "The word 'fox' is found in the text." is echoed.
Benefits of Using str_contains()
Over Other Methods
Using str_contains()
has benefits over other methods like strpos()
and stripos()
:
-
Better readability: The function name
str_contains()
clearly shows its purpose, making the code more readable. It removes the need for more checks on the returned value, as it returns a boolean. -
Simplicity: With
str_contains()
, you can check if a string contains a substring in one function call. You don't need to compare the returned value withfalse
or0
, as needed withstrpos()
andstripos()
. -
Better performance: The
str_contains()
function is made for performance and is faster than usingstrpos()
orstripos()
in most cases. It avoids returning the substring's position, which is not needed when you only want to know if the substring exists.
Method 3: Using Regular Expressions to Check if a PHP String Contains a Specific Word
Regular expressions (regex) are a tool for working with strings in PHP. They let you search for patterns in text, not just specific words, making them flexible for string manipulation tasks.
Using preg_match()
to Check if a String Contains a Word
The preg_match()
function in PHP lets you check if a string matches a regex pattern. You can use this to check if a string contains a specific word.
The preg_match()
function has this syntax:
preg_match(string $pattern, string $subject, array &$matches = null, int $flags = 0, int $offset = 0): int|false
$pattern
: The regex pattern to match against.$subject
: The string to search.$matches
: (Optional) An array to be filled with the results of the search.$flags
: (Optional) Flags to modify the behavior of the search.$offset
: (Optional) The offset in the string to start the search.
The function returns the number of matches found (0 or 1), or false
on error.
Here's an example of using preg_match()
to check if a string contains a word:
$text = "The quick brown fox jumps over the lazy dog";
$word = "fox";
$pattern = "/\b$word\b/";
if (preg_match($pattern, $text)) {
echo "The word '$word' is found in the string.";
} else {
echo "The word '$word' is not found in the string.";
}
In this code:
- The
$text
variable holds the string to search in. - The
$word
variable holds the word to search for. - The
$pattern
variable holds the regex pattern. It uses the\b
anchor to match word boundaries, making sure that only whole words are matched (so "fox" won't match "foxes"). preg_match()
checks if the$pattern
matches the$text
.- If a match is found, it returns 1, and the "word found" message is echoed.
- If no match is found, it returns 0, and the "word not found" message is echoed.
You can also use the $matches
parameter to get the matched text:
if (preg_match($pattern, $text, $matches)) {
echo "Matched text: " . $matches[0];
}
This would output: "Matched text: fox".
Example
-
Email validation: You can use a regular expression to check if a string is a valid email address. For example:
$email = "john.doe@example.com"; $pattern = "/^[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}$/"; if (preg_match($pattern, $email)) { echo "Valid email address"; } else { echo "Invalid email address"; }
-
Phone number extraction: You can use a regular expression to get phone numbers from a string. For example:
$text = "Call us at 123-456-7890 or 987-654-3210"; $pattern = "/\d{3}-\d{3}-\d{4}/"; if (preg_match_all($pattern, $text, $matches)) { echo "Phone numbers found: " . implode(", ", $matches[0]); } else { echo "No phone numbers found"; }
This would output: "Phone numbers found: 123-456-7890, 987-654-3210".
-
HTML tag removal: You can use a regular expression to remove HTML tags from a string. For example:
$html = "<p>Hello <b>world</b>!</p>"; $pattern = "/<\/?[a-z][a-z0-9]*[^<>]*>/i"; $text = preg_replace($pattern, "", $html); echo $text;
This would output: "Hello world!".
Advantages and Disadvantages of Using Regular Expressions
Regular expressions have advantages and disadvantages when checking if a string contains a word.
Advantages
- Flexibility: Regexes can match complex patterns, not just specific words. You can use character classes, anchors, quantifiers, and more to define precise patterns.
- Power: With regexes, you can do more than just check if a string contains a word. You can get parts of the string, replace text, split the string, and more.
Disadvantages
- Complexity: Regex syntax can be hard to read and write, especially for complex patterns. This can make code harder to understand and maintain.
- Performance: For simple text searches, using regexes might be slower than using string functions like
strpos()
orstr_contains()
. Regexes have to compile the pattern and then search the string, which takes time.
Other Methods to Check if a PHP String Contains a Specific Word
Using the strstr()
Function
The strstr()
function in PHP is another way to check if a string contains a specific word. It searches for the first occurrence of a substring in a string and returns the rest of the string from that point on.
The syntax for strstr()
is as follows:
strstr(string $haystack, string $needle, bool $before_needle = false): string|false
$haystack
: The string to search in.$needle
: The substring to search for.$before_needle
: (Optional) If set totrue
, the function returns the part of the string before the first occurrence of the substring. Default isfalse
.
Here's an example of using strstr()
to check if a string contains a word:
$text = "The quick brown fox jumps over the lazy dog";
$word = "fox";
if (strstr($text, $word)) {
echo "The word '$word' is found in the string.";
} else {
echo "The word '$word' is not found in the string.";
}
In this example, strstr()
searches for the word "fox" in the string $text
. If the word is found, the function returns the substring from the first occurrence of "fox" to the end of the string. The condition if (strstr($text, $word))
checks if the returned value is truthy (not false
), indicating that the word is found.
Example
Let's say you have a list of product descriptions and you want to check if a specific keyword is mentioned in each description. You can use strstr()
to search for the keyword in each description string.
$products = [
"Apple iPhone 12 Pro Max - 128GB - Pacific Blue",
"Samsung Galaxy S21 Ultra 5G - 256GB - Phantom Black",
"Google Pixel 5 - 128GB - Just Black"
];
$keyword = "iPhone";
foreach ($products as $product) {
if (strstr($product, $keyword)) {
echo "The product '$product' contains the keyword '$keyword'.
";
}
}
Output:
The product 'Apple iPhone 12 Pro Max - 128GB - Pacific Blue' contains the keyword 'iPhone'.
Splitting the String into an Array with explode()
Another approach to checking if a string contains a specific word is to split the string into an array of words using the explode()
function and then check if the word exists in the array.
The explode()
function breaks a string into an array by a specified delimiter. Here's the syntax:
explode(string $separator, string $string, int $limit = PHP_INT_MAX): array
$separator
: The delimiter used to split the string.$string
: The string to split.$limit
: (Optional) The maximum number of elements to return in the array. Default isPHP_INT_MAX
.
Here's an example of using explode()
to check if a string contains a word:
$text = "The quick brown fox jumps over the lazy dog";
$word = "fox";
$wordsArray = explode(" ", $text);
if (in_array($word, $wordsArray)) {
echo "The word '$word' is found in the string.";
} else {
echo "The word '$word' is not found in the string.";
}
In this code, explode(" ", $text)
splits the string $text
into an array of words using the space character as the delimiter. The resulting array $wordsArray
contains each word from the string as a separate element.
The in_array()
function is then used to check if the word $word
exists in the $wordsArray
. If the word is found, the function returns true
, and the corresponding message is echoed.
Example
Suppose you have a search functionality on your website where users can enter multiple keywords separated by commas. You can use explode()
to split the user's input into an array of keywords and then search for each keyword in your database or content.
$userInput = "apple, samsung, google";
$keywords = explode(", ", $userInput);
// Search for products containing any of the keywords
$products = [
"Apple iPhone 12 Pro Max - 128GB - Pacific Blue",
"Samsung Galaxy S21 Ultra 5G - 256GB - Phantom Black",
"Google Pixel 5 - 128GB - Just Black"
];
foreach ($products as $product) {
foreach ($keywords as $keyword) {
if (strstr($product, $keyword)) {
echo "The product '$product' matches the keyword '$keyword'.
";
}
}
}
Output:
The product 'Apple iPhone 12 Pro Max - 128GB - Pacific Blue' matches the keyword 'apple'.
The product 'Samsung Galaxy S21 Ultra 5G - 256GB - Phantom Black' matches the keyword 'samsung'.
The product 'Google Pixel 5 - 128GB - Just Black' matches the keyword 'google'.
Comparing the String with the Word Using Identical Operators
You can also check if a string contains a specific word by directly comparing the string with the word using the identical operator ===
.
Here's an example:
$text = "fox";
$word = "fox";
if ($text === $word) {
echo "The string is identical to the word '$word'.";
} else {
echo "The string is not identical to the word '$word'.";
}
In this case, the string $text
is directly compared with the word $word
using the ===
operator. If the string and the word are identical, the condition if ($text === $word)
evaluates to true
, and the corresponding message is echoed.
However, this method has limitations:
- It only works if the string exactly matches the word. If the string contains additional characters or the word is a substring of the string, the comparison will return
false
. - It is case-sensitive. If the string and the word have different cases, the comparison will return
false
.
Therefore, this method is only suitable when you want to check if a string is identical to a specific word, rather than checking if the string contains the word as a substring.
Example
Consider a scenario where you have a list of predefined categories and you want to check if a given string matches any of those categories exactly.
$categories = ["Electronics", "Clothing", "Home"];
$productCategory = "Electronics";
if (in_array($productCategory, $categories, true)) {
echo "The product category '$productCategory' is valid.";
} else {
echo "The product category '$productCategory' is not valid.";
}
In this example, the in_array()
function with the third parameter set to true
performs a strict comparison (identical operator ===
) between the $productCategory
and each element of the $categories
array. If an exact match is found, the product category is considered valid.
Method | Description | Use Case |
---|---|---|
strstr() |
Searches for the first occurrence of a substring in a string | Check if a string contains a specific word as a substring |
explode() |
Splits a string into an array by a specified delimiter | Split a string into words and check if a specific word exists in the array |
Identical Operator === |
Compares a string directly with a word | Check if a string exactly matches a specific word |