Optimizing Regex Usage in PHP

Regular expressions are very heavy and relatively slow-performing things. When there is an alternative solution, it is advisable to use it.

Let's look at an example. Suppose we need to check if a certain string starts with an exclamation mark. A certain programmer solved this problem via a regex:

php<?php
  if (preg_match('#^!#', $str)) {
    echo 'yes';
  } else {
    echo 'no';
  }
?>

However, such a task has a much faster solution:

php<?php
  if ($str[0] == '!') {
    echo 'yes';
  } else {
    echo 'no';
  }
?>

Regexes are very heavy and relatively slow-performing things. Always, where there is an alternative solution, it is advisable to use it.

Задание 1

In the following code, a certain programmer checks if the string contains the substring '333'. Optimize this programmer's solution.

Here is the code:

php<?php
  $str = '1233345';
  
  if (preg_match('#333#', $str)) {
    echo 'exists';
  } else {
    echo 'does not exist';
  }
?>
Задание 2

In the following code, a certain programmer checks if the string ends with .html. Optimize this programmer's solution.

Here is the code:

php<?php
  $str = 'index.html';
  
  if (preg_match('#\.html$#', $str)) {
    echo 'yes';
  } else {
    echo 'no';
  }
?>
Задание 3

Write code that will check if the string ends with .png or with .jpg.