String contains another string

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?
strpos 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.

This entry was posted in PHP. Bookmark the permalink.

Leave a Reply

Your email address will not be published. Required fields are marked *

*

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>