When looking for substrings in strings, strpos() is used (and its counterpart strrpos(), which searches from the end of the string). The tricky thing about this function is that it returns the index of the first occurrence of the substring, or false otherwise. That means that the preceding code snippet is incorrect. The preceding code snippet is incorrect because if $string happens to start with $substring, strpos() returns 0, which evaluates to false. Therefore, a comparison using === or !== must be used to take the data type into account. The code at the beginning of this phrase shows how to correctly use strpos(). Understanding Regular ExpressionsRegular expressions are, to put it simple, patterns that can be matched with strings. Two kinds of regular expressions are available in PHPPOSIX regular expressions and PHP regular expressions. The former can be installed when configuring PHP with the switch --with-regex. Windows users do not have to do this; the support for POSIX Regex is enabled by default. The alternatives are Perl-compatible regular expressions (PCRE). PCRE are often said to be faster, and do offer more features. This functionality is enabled in PHP by default; however, if you compile PHP by yourself, you can deactivate PCRE using the switch --without-pcre-regex. A pattern in a regular expression contains a string that can be searched for in a larger string. However, this can also be done (faster) using strpos(). The advantage of regular expressions is that some special features such as wildcards are available. Table 1.2 shows some special characters and their meaning.
Other special characters and expressions are available, for instance a character that refers to a digit. However, this differs between POSIX and PCRE, which in the example use [:digit:] and \d, respectively. |