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
if (preg_match('#^!#', $str)) {
echo 'yes';
} else {
echo 'no';
}
?>
However, such a task has a much faster solution:
<?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.
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
$str = '1233345';
if (preg_match('#333#', $str)) {
echo 'exists';
} else {
echo 'does not exist';
}
?>
In the following code, a certain programmer checks
if the string ends with .html.
Optimize this programmer's solution.
Here is the code:
<?php
$str = 'index.html';
if (preg_match('#\.html$#', $str)) {
echo 'yes';
} else {
echo 'no';
}
?>
Write code that will check if the string ends
with .png or with .jpg.