Regex
The biggest problem of regex is readability. Please read a perfect article Writing better Regular Expressions in PHP on this topic. There is nothing to add.
You can also use DEFINE to declare recurring patterns in you regex. Here's an example regex that declares attr, which captures HTML attributes and its use-case in declaring an image tag. It also uses sprintf to create reusable regex definitions.
PHP
class RegexHelper
{
/** @return array<string, string> */
public function images(string $htmlContent): array
{
$pattern = '
(?'image' # Capture named group
(?P>img) # Recurse img subpattern from definitions
)
'
preg_match_all($this->createRegex($pattern), $htmlContent, $matches);
return $matches['image'];
}
private function createRegex(string $pattern): string
{
return sprintf($this->getDefinitions(), preg_quote($pattern, '~'));
}
private function getDefinitions(): string
{
return "~
(?(DEFINE) # Allows defining reusable patterns
(?'attr'(?:\s[^>]++)?) # Capture HTML attributes
(?'img'<img(?P>params)>) # Capture HTML img tag with its attributes
)
%s #Allows adding dynamic regex using sprintf
~ix";
}
}
You can use Regex101 to test your patterns.
