How to check if a string contains a substring
Short answer
str_contains() returns true when the substring is found:
<?php
var_dump(str_contains('Hello, world', 'world'));Output:
bool(true)Case-insensitive search
The search is case-sensitive. To ignore case, convert both strings to lowercase with mb_strtolower():
<?php
$text = 'Hello, World';
var_dump(str_contains(mb_strtolower($text), mb_strtolower('WORLD')));Output:
bool(true)Finding the position
If you need to know where the substring is, use mb_strpos(). It returns the position or false:
<?php
var_dump(mb_strpos('Hello, world', 'world'));Output:
int(7)Functions used in this recipe
- str_contains — Checks whether a string contains a given substring.
- mb_strpos — Finds the position of the first occurrence of a substring.
- mb_strtoupper — Converts a string to uppercase.