Skip to content

Instantly share code, notes, and snippets.

@Kcko
Last active November 28, 2025 09:50
Show Gist options
  • Select an option

  • Save Kcko/d5abbdfe796da4225821fcb7356a315c to your computer and use it in GitHub Desktop.

Select an option

Save Kcko/d5abbdfe796da4225821fcb7356a315c to your computer and use it in GitHub Desktop.
<?php
$regex1 = '/(\d+) \1/'; // Backreference
$regex2 = '/(\d+) (?1)/'; // Subroutine
100 100 // ✅ only backreference
100 200 // ✅ both!
// https://github.com/Hamz-a/php-regex-best-practices/blob/master/07%20Writing%20modular%20regexes.md
// named subroutines
$regex = '/(?<number>\d+),(?&number)/'; // Named subroutine
// advanced
$regex = <<<'regex'
~
(?(DEFINE)
(?<id>\d+)
(?<username>user(?&id))
(?<protocol>https?|ftp)
(?<domain>example[.]com)
(?<url>(?&protocol)://(?&domain)/users/(?&id)/(?&username)/?)
)
^(?&url)$ # Anchor our match
~x
regex;
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment