How to check if a String contains a Specific Character in PHP ?
Last Updated :
13 Feb, 2024
In PHP, determining whether a string contains a specific character is a common task. Whether you’re validating user input, parsing data, or performing text processing, PHP provides several methods to check for the presence of a particular character within a string efficiently.
Example: Implementation to check if a string contains a specific character using the strpos( ) function
PHP
<?php
$string = "Hello, world!" ;
$char = "o" ;
if ( strpos ( $string , $char ) !== false) {
echo "The string contains the character '$char'." ;
} else {
echo "The string does not contain the character '$char'." ;
}
?>
|
Output
The string contains the character 'o'.
Example: Implementation to check if a string contains a specific character using strstr( ) function.
PHP
<?php
$string = "Hello, world!" ;
$char = "o" ;
if ( strstr ( $string , $char ) !== false) {
echo "The string contains the character '$char'." ;
} else {
echo "The string does not contain the character '$char'." ;
}
?>
|
Output
The string contains the character 'o'.
Difference between strops() and Strstr() Methods
strpos() Function |
strstr() Function |
Finds the position of the first occurrence of a substring within a string |
Finds the first occurrence of a substring within a string and returns the portion of the string starting from that occurrence |
Returns the position of the substring if found, otherwise returns a false |
Returns the portion of the string starting from the first occurrence of the substring if found, otherwise returns a false |
Suitable for checking the presence and position of a specific character |
Useful when you need to extract a portion of the string starting from the first occurrence of a substring |
Share your thoughts in the comments
Please Login to comment...