PHP code example of folour / regex

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

    

folour / regex example snippets


composer 

 declare(strict_types=1);

use Folour\Regex\Regex;

$content = 'Test [string], test [value]';
$re = new Regex($content);

/*
 * Replace example
 * this method returns a new instance with replaced string as content
 * Regex object returns content when converts to string
 */
$replaced = $re->replace('/test/i', 'replaced');
//Converts to string and print text 'replaced [string], replaced [value]'
echo $replaced;

//fluent replacement
$replaced = $re
    ->replace('/test/i', 'replaced')
    ->replace('/replaced/', 'double_replaced');

echo $replaced;//'double_replaced [string], double_replaced [value]

//callback replacement
$replaced = $re->replace('/\[([a-z]+)\]/i', function($matches) {
    return sprintf('[replaced_%s]', $matches[1]);
});
echo $replaced; //'Test [replaced_string], test [replaced_value]'

/*
 * find matches
 */
//first match
$m = $re->find('/\[(?P<matched>[a-z]+)\]/');
var_dump($m);
// array(
//   'matched' => 'string'
// )

//all matches
$m = $re->findAll('/\[(?P<matched>[a-z]+)\]/');
var_dump($m);
// array(
//   0 => array(
//     'matched' => 'string'
//   ),
//   1 => array(
//     'matched' => 'value'
//   )
// )

/*
 * Split string
 */
$parts = $re->split('/\,\s?/');
var_dump($parts);
// array(
//   0 => 'Test [string]',
//   1 => 'test [value]'
// )