PHP code example of regex-guard / regex-guard

1. Go to this page and download the library: Download regex-guard/regex-guard library. Choose the download type require.

2. Extract the ZIP file and open the index.php.

3. Add this code to the index.php.
    
        
<?php
require_once('vendor/autoload.php');

/* Start to develop here. Best regards https://php-download.com/ */

    

regex-guard / regex-guard example snippets


$guard = \RegexGuard\Factory::getGuard();

if($guard->isRegexValid($regexp)) {
    // valid
}
else {
    // invalid
}

$guard->isRegexValid('/\w{0,1}/');
// true, regex is valid

$guard->isRegexValid('/\w{1,0}/');
// false, compilation fails: quantifiers are out of order

$guard->isRegexValid('/(\w)(?2)/');
// false, compilation fails: reference to non-existent subpattern at offset 7

$guard->validateRegexOrFail('/(\w)(?2)/');
// throws: compilation fails: reference to non-existent subpattern at offset 7

try {
    if($regexGuard->match($pattern, $subject)) {
        // match
    } else {
        // no match
    }
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

try {
    $found = $regexGuard->matchAll($pattern, $subject, $matches);
    if($found) {
        foreach($matches[0] as $match) {
            //
        }
    }
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

try {
    $result = $regexGuard->filter($pattern, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

try {
    $result = $regexGuard->grep($pattern, $input);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

try {
    $result = $regexGuard->replace($pattern, $replacement, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

try {
    $list = $regexGuard->split($pattern, $subject);
} catch(\RegexGuard\RegexException $e) {
    // handle the invalid regexp
}

$guard = \RegexGuard\Factory::getGuard()->throwOnException(false);
                        
if(1 === $guard->match('#foo#y', 'bar')) {
// ^ strict check            ^ bad regex: Unknown modifier 'y' on line 1
}

use RegexGuard\ErrorHandler;
use RegexGuard\Sandbox;
use RegexGuard\RegexGuard;

$guard = new RegexGuard(new Sandbox(new ErrorHandler));