PHP code example of jeroenvanderlaan / regexp

1. Go to this page and download the library: Download jeroenvanderlaan/regexp 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/ */

    

jeroenvanderlaan / regexp example snippets



$matcher = new Matcher();
$regexp = new Regexp("(exam)ple");

$match = $matcher->match($regexp, "An example string");
$match->getSubject(); //"An example string"
$match->getMatch(); //"example"
$match->getOffset(); //3
$match->getGroups()[0]->getMatch(); //"exam"


$matcher = new Matcher();
$regexp = new Regexp("foo|bar");

$match = $matcher->match($regexp, "foobar");
$match->getSubject(); //"foobar"
$match->getMatch(); //"foo"
$match->getOffset(); //0

$matches = $matcher->matchAll($regexp, "foobar");
$match = array_pop($matches);
$match->getSubject(); //foobar
$match->getMatch(); //bar
$match->getOffset(); //3


$replacer = new Replacer();
$regexp = new Regexp("foo|bar");
$callback = function (string $match) {
	return strrev($match);
};

$replaced = $replacer->replace($regexp, "foobar", $callback);
(string) $replaced; //oofrab


$replaced->getReplacedString(); //oofrab
$replaced->getOriginalString(); //foobar
$replacements = $replaced->getReplacements();
$replacements[0]->getMatch(); //foo
$replacements[0]->getReplacement(); //oof
$replacements[1]->getMatch(); //bar
$replacements[1]->getReplacement(); //rab


$unreplacer = new Unreplacer();
$unreplacer->unreplace("rab", ...$replacements); //returns "bar"
$unreplacer->unreplace("oofrabbaz", ...$replacements); //returns foobarbaz


$substitutor = new Substitutor();
$regexp = new Regexp("\<\>");
$substituted = $substitutor->substitute($regexp, "<foo></foo>"); //substitutes all "<" and ">"
$matcher->match($regexp, (string) $substituted); //returns null


$substitutes = $substituted->getReplacements();
$unreplacer = new Unreplacer();
$unreplaced = $unreplacer->unreplace((string) $substituted, ...$substitutes);
//unreplaced is now "<foo></foo>"