Created
December 29, 2013 11:06
-
-
Save dkreuer/8169343 to your computer and use it in GitHub Desktop.
Script to demonstrate the PCRE ability to define subpattern.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
$testString = '192.168.0.1'; | |
$regex1 = trim(' | |
^ # Matches begin of string | |
( | |
\d| # Matches either a single digit or | |
[1-9]\d| # a number between 10 and 99 or | |
1\d\d| # a number between 100 and 199 or | |
2[0-4]\d| # a number between 200 and 249 or | |
25[0-5] # a number between 250 and 255 | |
) | |
( | |
\. # Matches the dot character literally "." | |
( | |
\d| # Matches either a single digit or | |
[1-9]\d| # a number between 10 and 99 or | |
1\d\d| # a number between 100 and 199 or | |
2[0-4]\d| # a number between 200 and 249 or | |
25[0-5] # a number between 250 and 255 | |
) | |
) | |
{3} # Matches the previous group exactly three times | |
$ # Matches end of string | |
'); | |
$regex2 = trim(' | |
(?(DEFINE)(?<bg>25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)) # Defines a bytegroup | |
^ # Matches begin of string | |
(?&bg) # References a bytegroup | |
( | |
\. # Matches the dot literally "." | |
(?&bg) # References a bytegroup | |
) | |
{3} # Matches the previous group exactly three times | |
$ # Matches end of string | |
'); | |
$regex3 = trim(' | |
(?(DEFINE)(?<byteg>25[0-5]|2[0-4]\d|1\d\d|[1-9]\d|\d)) # Defines a bytegroup | |
(?(DEFINE)(?<dot>\.)) # Defines the dot literally | |
^(?&byteg)(?&dot)(?&byteg)(?&dot)(?&byteg)(?&dot)(?&byteg)$ | |
'); | |
echo "Test: $testString" . PHP_EOL; | |
echo "Regex:" . PHP_EOL . $regex1 . PHP_EOL; | |
echo "Result: " . preg_match("/$regex1/x", $testString, $matches) . PHP_EOL; | |
echo "Matches: "; print_r($matches); | |
echo PHP_EOL; | |
echo "Test: $testString" . PHP_EOL; | |
echo "Regex:" . PHP_EOL . $regex2 . PHP_EOL; | |
echo "Result: " . preg_match("/$regex2/x", $testString, $matches) . PHP_EOL; | |
echo "Matches: "; print_r($matches); | |
echo PHP_EOL; | |
echo "Test: $testString" . PHP_EOL; | |
echo "Regex:" . PHP_EOL . $regex3 . PHP_EOL; | |
echo "Result: " . preg_match("/$regex3/x", $testString, $matches) . PHP_EOL; | |
echo "Matches: "; print_r($matches); | |
echo PHP_EOL; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment