PHP code example of sl5net / preg-contentfinder

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

    

sl5net / preg-contentfinder example snippets

     

regContentFinder\PregContentFinder;

// Example 1: Simple Extraction
$sourceText = "Some text [สำคัญ data1] and [other {data2}] stuff.";
$finder = new PregContentFinder($sourceText, '[', ']');

$content1 = $finder->getContent(); // Finds first match
// $content1 = "สำคัญ data1"

$content2 = $finder->getContent(); // Finds next match (if state is managed correctly)
// This depends on how getContent updates the internal position.
// Often used in a loop with setPosOfNextSearch or getBorders.

// Example 2: Transformation with Callback
$source = "Process {A{B}C} and {D}.";
$finder = new PregContentFinder($source, '{', '}');

$result = $finder->getContent_user_func_recursive(
    function ($cut, $deepCount) {
        // $cut['middle'] contains content between {} for the current level
        // $deepCount indicates nesting level (0 for outermost)
        $cut['middle'] = "[$deepCount:" . strtoupper($cut['middle']) . "]";
        return $cut; // Return modified segment parts
    }
);

// Expected $result might be something like:
// Process [0:A[1:B]C] and [0:D].
// (Exact output depends on internal recursive assembly logic)
echo $result;


use SL5\PregContentFinder\PregContentFinder;

$source = 'a{b{B}}';
$finder = new PregContentFinder($source, '{', '}'); // Set delimiters in constructor

$transformed = $finder->getContent_user_func_recursive(
    function ($cut) { // $cut is an array: ['before' => ..., 'middle' => ..., 'behind' => ...]
        // This simple callback just reassembles with new brackets
        // A more robust callback would only modify $cut['middle'] for this specific example.
        // The class logic for getContent_user_func_recursive handles the assembly.
        // Assuming the callback returns the new middle part:
        return $cut['before'] . '[' . $cut['middle'] . ']' . $cut['behind'];
    }
);
// To purely replace delimiters and keep content, often simpler regex is enough.
// The power of user_func_recursive comes with complex logic in the callback.

// For simple delimiter replacement, a direct string replace after extraction might be easier,
// or a callback that only returns the $cut['middle'] unmodified if the goal
// is just to change the delimiters during reassembly by the main class (if it supports that).

// Let's assume a more practical callback for this simple case,
// where the class itself handles outer delimiters and recursion passes inner content:
$finder = new PregContentFinder($source, '{', '}');
$transformed = $finder->getContent_user_func_recursive(
    function ($cut) {
        // The callback is called for the content *inside* each {} pair.
        // For a{b{B}}, first call $cut['middle'] = "b{B}"
        // Recursive call for {B}, $cut['middle'] = "B"
        // $cut['before'] and $cut['behind'] are relative to the current segment.
        
        // To achieve a[b[B]], the callback needs to be smart or the class
        // needs to offer specific ways to replace delimiters.
        // A more direct way for *this specific example* if just changing delimiters:
        // This is conceptual if the class provides these replacement delimiters in callback.
        $newOpen = '[';
        $newClose = ']';
        $cut['before'] = str_replace('{', $newOpen, $cut['before']); // Risky, better done by class
        $cut['middle'] = $cut['middle']; // Content stays same
        $cut['behind'] = str_replace('}', $newClose, $cut['behind']); // Risky

        // A cleaner callback just processes $cut['middle']
        // $cut['middle'] = "TRANSFORMED_" . $cut['middle'];
        return $cut;
    }
);
// The example below is more realistic for the callback's role.
// For the simple a{b{B}} => a[b[B]] example, it implies the *class* is configured
// with new delimiters for output, or the callback is very simple.

// More realistic callback for transformation:
$finder = new PregContentFinder('a{b{B}}', '{', '}');
$result = $finder->getContent_user_func_recursive(function($cut) {
    $cut['middle'] = '*' . $cut['middle'] . '*'; // Example: wrap middle content with asterisks
    return $cut;
});
// $result would be 'a{*b{B}*}' if non-recursive or 'a{*b{*B*}*}' if recursive on middle.
// The original example's output 'a[b[B]]' implies the class itself was configured to output
// different delimiters, or the callback was extremely simple for that specific transformation.

// The key is the callback operates on $cut['middle'] (the content within the current delimiters).
// The examples provided in the original README are about the *final output* after the
// class (with a suitable callback) has processed the input.


use SL5\PregContentFinder\PregContentFinder;

$source = 'if(X1){$X1;if(X2){$X2;}}';
$finder = new PregContentFinder($source, '{', '}');

$indented = $finder->getContent_user_func_recursive(
    function ($cut, $deepCount, $callsCount, $posList0, $originalSegmentContent) {
        $indentChar = "  "; // Two spaces for indentation
        $newline = "\n";
        
        $currentIndent = str_repeat($indentChar, $deepCount);
        $innerIndent = str_repeat($indentChar, $deepCount + 1);

        // Process $cut['middle'] for newlines and apply indentation
        $middleLines = explode(';', rtrim($cut['middle'], ';')); // Split by semicolon for example
        $processedMiddle = "";
        foreach ($middleLines as $line) {
            if (trim($line) !== "") {
                $processedMiddle .= $innerIndent . trim($line) . ";" . $newline;
            }
        }
        // Remove last semicolon and newline if present
        $processedMiddle = rtrim(rtrim($processedMiddle, $newline), ';');


        // Reconstruct the segment for this level
        // The class will handle how $cut['before'] and $cut['behind'] are used from outer levels.
        // The callback focuses on transforming its $cut['middle'].
        $cut['middle'] = $newline . $processedMiddle . $newline . $currentIndent;
        
        // For the example output, the class also needs to be aware of replacing
        // the original delimiters with new ones that include newlines and outer indentation.
        // e.g., $cut['before'] might become $cut['before'] . "[" . $newline
        // This