PHP code example of mcustiel / php-simple-regex

1. Go to this page and download the library: Download mcustiel/php-simple-regex 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/ */

    

mcustiel / php-simple-regex example snippets


use Mcustiel\PhpSimpleRegex\Executor as RegexExecutor;

$regexFacade = new RegexExecutor();

try {
    $result = $regexFacade->getAllMatches('/\d+/', 'ab12cd34ef56');
    echo 'Number of matches: ' . $result->getMatchesCount() . PHP_EOL; // Prints 3
    echo 'First match: ' . $result->getMatchAt(0)->getFullMatch() . PHP_EOL; // Prints 12
    
    // Iterate over results
    foreach ($result as $index => $match) {
        echo "Match at index {$index} is " . $match->getFullMatch() . PHP_EOL; 
    }
} catch (\Exception $e) {
    echo 'An error occurred executing getAllMatches';
}

try {
    $result = $regexFacade->getOneMatch('/\d+/', 'ab12cd34ef56');
    if (!empty($result)) {
        echo 'Match: ' . $result->getFullMatch() . PHP_EOL; // Prints 12
    }
} catch (\Exception $e) {
    echo 'An error occurred executing getOneMatch';
}

try {
    if ($regexFacade->match('/\d+/', 'ab12cd34ef56')) {
        echo 'String matches pattern.'. PHP_EOL;
    } else {
        echo 'String does not match pattern.'. PHP_EOL;
    }
} catch (\Exception $e) {
    echo 'An error occurred executing match';
}

try {
    // Subject can also be an array.
    $result = $this->executor->replaceAndCount('/\d+/', 'potato', 'ab12cd34ef56');
    echo 'Number of replacements: ' . $result->getReplacements() . PHP_EOL;
    echo 'Replaced string: ' . $result->getResult() . PHP_EOL;
} catch (\Exception $e) {
    echo 'An error occurred executing replaceAndCount';
}

try {
    // Subject can also be a string.
    $result = $this->executor->replaceAndCount('/\d+/', 'potato', ['ab12cd34ef56', 'ab12cd78ef90']);
    echo 'Replaced strings: ' . print_r($result->getResult(), true) . PHP_EOL;
} catch (\Exception $e) {
    echo 'An error occurred executing replace';
}

try {
    // Subject can also be an array.
    $result = $this->executor->replaceCallback('/\d+/', function () { return 'potato'; }, 'ab12cd34ef56');
    echo 'Replaced string: ' . $result->getResult() . PHP_EOL;
} catch (\Exception $e) {
    echo 'An error occurred executing replaceCallback';
}

try {
    // Subject can also be an array.
    $result = $this->executor->replaceCallback('/\d+/', function () { return 'potato'; }, 'ab12cd34ef56');
    echo 'Number of replacements: ' . $result->getReplacements() . PHP_EOL;
    echo 'Replaced string: ' . $result->getResult() . PHP_EOL;
} catch (\Exception $e) {
    echo 'An error occurred executing replaceCallbackAndCount';
}