Home >Backend Development >PHP Tutorial >How Can I Make PHP\'s `preg_match()` Case-Insensitive?
Ignoring Case in preg_match()
When performing pattern matching using PHP's preg_match() function, you may encounter situations where case sensitivity becomes a factor. To make preg_match() case insensitive, you can employ the following technique:
Solution:
The key to case insensitivity in preg_match() lies in adding the i modifier after the delimiter. For instance, consider the following case:
preg_match("#(.{100}$keywords.{100})#", strip_tags($description), $matches);
In this example, the goal is to display 100 characters on each side of the search string $keywords. While this code is functional, it's case sensitive. To make it case insensitive, add the i modifier as follows:
preg_match("#(.{100}$keywords.{100})#i", strip_tags($description), $matches);
Alternatively, if your delimiter is a forward slash "/", you can add the i modifier after it, as seen in the following example:
preg_match("/your_regexp_here/i", $s, $matches); // i means case insensitive
Effect of the i Modifier:
By specifying the i modifier, you instruct preg_match() to ignore case differences in the matching process. This means that if the target string contains either uppercase or lowercase letters matching the pattern, the match will still succeed.
Example:
Consider the pattern:
"/abc/"
With the i modifier applied, this pattern will match the strings "ABC", "abc", and "aBc". Without the i modifier, only the exact string "abc" would be matched.
The above is the detailed content of How Can I Make PHP\'s `preg_match()` Case-Insensitive?. For more information, please follow other related articles on the PHP Chinese website!