---
title: "Regex"
canonical_url: "https://handbook.propay.co.za/php/regex"
---
# Regex

The biggest problem of regex is readability. Please read a perfect article [Writing better Regular Expressions in PHP](https://php.watch/articles/php-regex-readability) on this topic. There is nothing to add.

You can also use `DEFINE` to declare recurring patterns in your 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.

<code-group>

```php [RegexHelper.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";
    }
}
```

</code-group>

You can use [Regex101](https://regex101.com/) to test your patterns.


## Sitemap

See the full [sitemap](https://handbook.propay.co.za/sitemap.md) for all pages.
