PHP code example of s9e / regexp-builder

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

    

s9e / regexp-builder example snippets


// Use the PHP factory to generate a PHP regexp
$builder = s9e\RegexpBuilder\Factory\PHP::getBuilder();
echo '/', $builder->build(['foo', 'bar', 'baz']), '/';

// Without any modifiers, PCRE operates on bytes
$builder = s9e\RegexpBuilder\Factory\PHP::getBuilder();
echo '/', $builder->build(['☺', '☹']), "/\n";

// The 'u' flag enables Unicode mode in PCRE
$builder = s9e\RegexpBuilder\Factory\PHP::getBuilder(modifiers: 'u');
echo '/', $builder->build(['☺', '☹']), '/u';

$builder = s9e\RegexpBuilder\Factory\JavaScript::getBuilder();
echo '/', $builder->build(['😁', '😂']), "/\n";

// The 'u' flag enables Unicode mode in JavaScript RegExp
$builder = s9e\RegexpBuilder\Factory\JavaScript::getBuilder(flags: 'u');
echo '/', $builder->build(['😁', '😂']), '/u';

$builder = new s9e\RegexpBuilder\Builder;
$builder->meta->set('?', '.');
$builder->meta->set('*', '.*');

echo '/', $builder->build(['foo?', 'bar*']), '/';

$builder = new s9e\RegexpBuilder\Builder;
$builder->meta->set('\\d', '\\d');

echo '/', $builder->build(['a', 'b', '\\d']), '/';

$builder = new s9e\RegexpBuilder\Builder(
	meta: new s9e\RegexpBuilder\Meta(['?' => '.', '*' => '.*'])
);

echo '/', $builder->build(['foo?', 'bar*']), '/';

// Use the PHP factory to generate a PHP regexp with ~ as a delimiter
$delimiter = '~';
$builder   = s9e\RegexpBuilder\Factory\PHP::getBuilder(delimiter: $delimiter);

// In this example, we want to use non-capture groups that reset group numbers
// As per https://www.pcre.org/current/doc/html/pcre2syntax.html#TOC1
$builder->serializer->groupType = s9e\RegexpBuilder\GroupType::NonCaptureReset;

// Syntactic sugar
function expr(string $expr)
{
	return new s9e\RegexpBuilder\Expression($expr);
}

// Here we split each route into a mix of literals and regular expressions
$regexp = $builder->build([
	['/', expr('(*:home)')],
	['/admin', expr('(*:admin_index)')],
	['/admin/login', expr('(*:admin_login)')],
	['/admin/logout', expr('(*:admin_logout)')],
	['/admin/product', expr('(*:admin_product_store)')],
	['/admin/product/', expr('(\d+)'), expr('(*:admin_product_show)')],
	['/admin/product/', expr('(\d+)'), '/edit', expr('(*:admin_product_edit)')],
	['/shop', expr('(*:shop_index)')],
	['/shop/product', expr('(*:shop_product_index)')],
	['/shop/product/', expr('(\d+)'), expr('(*:shop_product_show)')]
]);
$regexp = $delimiter . '^' . $regexp . '$' . $delimiter;

// Let's see what the regexp looks like
echo "$regexp\n\n";

// Let's test our new regexp
preg_match($regexp, '/admin/product/123', $m);
print_r($m);