In this paper, I will bring a simple command (condition) in PHP to check whether a string contains another string. Unfortunately, PHP don’t have function contains, and we must create it yourself.
1st Testing whether a string contains a substring.
if (strpos($retezec,$hledany_vyraz) !== false) { echo 'String found'; }
2nd The condition whether a string contains a given substring.
if (strpos($retezec,$hledany_vyraz) === false) { echo 'String not found'; }
3rd A comprehensive test on the contents of the substring in string
if (strpos($retezec,$hledany_vyraz) === false) { echo 'string not found'; } else { echo 'string found'; }
How does it works? strong>
strpos em> returns the position of substring in the text. If the text does not contains substring, it returns false. As can be just the substring in the first place, you must use == instead of === operator (or !==).
Important Notice! Do not use for test commands strstr or ereg! Both commands are too computationally and memory intensive.