Current Location: Home> Latest Articles> Practical Methods to Check if a String Contains Specific Characters in PHP

Practical Methods to Check if a String Contains Specific Characters in PHP

M66 2025-08-04

Methods to Check if a String Contains Specific Characters in PHP

In PHP development, determining whether a string contains certain characters or substrings is a common requirement. PHP offers various functions to achieve this, which are introduced below.

Using strpos() Function

The strpos() function searches for the first occurrence of a character or substring in a string. If found, it returns the position index of the character; otherwise, it returns false.

$string = 'Hello World';
$char = 'W';

if (strpos($string, $char) !== false) {
  echo 'The string contains the character "' . $char . '"';
} else {
  echo 'The string does not contain the character "' . $char . '"';
}

Using strstr() Function

The strstr() function searches a string for the first occurrence of a specified character or substring. If found, it returns the portion of the string from the matched character to the end; otherwise, it returns false.

$string = 'Hello World';
$substring = 'World';

if (strstr($string, $substring)) {
  echo 'The string contains the substring "' . $substring . '"';
} else {
  echo 'The string does not contain the substring "' . $substring . '"';
}

Using preg_match() Function

The preg_match() function uses regular expressions to match patterns in a string. It is suitable for more complex character detection needs.

/$char/

$string = 'Hello World';
$char = 'W';

if (preg_match('/' . $char . '/', $string)) {
  echo 'The string contains the character "' . $char . '"';
} else {
  echo 'The string does not contain the character "' . $char . '"';
}

Other Common Methods

  • mb_strpos(): Supports searching in multibyte character strings, suitable for languages like Chinese.
  • preg_grep(): Filters an array of strings based on a regular expression.
  • in_array(): Used with arrays to check if a string exists within an array.

The methods introduced above help you flexibly check string content based on different requirements. Mastering these functions can significantly improve the efficiency and accuracy of PHP string handling.