⊗ppPmRgSCh 245 of 447 menu

Checking a String with a Regex in PHP

The capabilities of regular expressions are far from exhausted by search and replace. There is also the function preg_match, which checks if a string contains a match with the regex. The first parameter of the function takes the regular expression, and the second - the string to search in.

In this case, if there are many matches, - the function will find only the first one and finish its work. Therefore, the function outputs either 1, or 0 and is used to answer the question 'is the sought-after present in the string or not'. Returns one - means yes (and how many times - is unclear), returns zero - means no.

Let's look at some examples. Let's check, if the string contains a substring consisting of the letter 'a', repeated one or more times:

<?php echo preg_match('#a+#', 'eee aaa bbb'); // outputs 1 ?>

And now our string does not contain the sought-after, and the function will output 0:

<?php echo preg_match('#a+#', 'eee bbb'); // outputs 0 ?>

Determine if the string contains 3 digits in a row.

Determine if the passed string starts with http.

Determine if the passed string starts with http or with https.

Determine if the passed string ends with the extension txt, html or php.

Determine if the passed string ends with the extension jpg or jpeg.

byenru