PHP code example of maestroerror / eloquent-regex

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

    

maestroerror / eloquent-regex example snippets


EloquentRegex::source('[email protected]')->email()->check();

$link = 'https://www.example.com/home';
$isValidUrl = EloquentRegex::source($link)->url()->check(); // true

$isStrong = EloquentRegex::source("StrongP@ssw0rd")->password(function($options) {
    $options->minLength(8)->minUppercase(1)->minNumbers(1)->minSpecialChars(1);
})->check(); // true

EloquentRegex::start("#hello #world This is a #test")->hash()->text()->get();
// ['#hello', '#world', '#test']

use Maestroerror\EloquentRegex\EloquentRegex;

use Maestroerror\EloquentRegex\Facades\EloquentRegex;

EloquentRegex::source("Support: [email protected]; Info: [email protected]")
    ->email()
    ->get();
// Returns: ["[email protected]", "[email protected]"]

EloquentRegex::start("#hello #world This is a #test")
    ->hash()->text()
    ->get();
// Returns: ['#hello', '#world', '#test']

EloquentRegex::source("[email protected]")
    ->email()->check();
// Returns: true

EloquentRegex::start("#test")
    ->hash()->text()
    ->check();
// Returns: true

EloquentRegex::source("Support: [email protected]; Info: [email protected]")
    ->email()->checkString();
// Returns: true

EloquentRegex::start("#hello #world This is a #test")
    ->hash()->text()
    ->checkString();
// Returns: true

EloquentRegex::source("Support: [email protected]; Info: [email protected]")
    ->email()->count();
// Returns: 2

EloquentRegex::start("#hello #world This is a #test")
    ->hash()->text()
    ->count();
// Returns: 3

EloquentRegex::source("Support: [email protected]; Info: [email protected]")
    ->email()
    ->replace(function($foundItem) {
        return "<span>" . $foundItem . "</span>";
    });
// Returns: "Support: <span>[email protected]</span>; Info: <span>[email protected]</span>"

EloquentRegex::start("This is a #test")
    ->hash()->text()
    ->replace(function($foundItem) {
        return "<a href='$foundItem'>" . $foundItem . "</a>";
    });
// Returns: "This is a <a href='#test'>#test</a>"

EloquentRegex::builder()->start()
    ->textLowercase()
    ->atSymbol()
    ->textLowercase()
    ->dot()
    ->textLowercaseRange(2, 4)
    ->toRegex();
// Returns: "[a-z]+@[a-z]+\.[a-z]{2,4}"

EloquentRegex::source(
    "
    Whose woods these are I think I know.\n
    His house is in the village though;\n
    He will not see me stopping here\n
    To watch his woods fill up with snow.\n
    \n
    The woods are lovely, dark and deep,\n
    But I have promises to keep,\n
    And miles to go before I sleep,\n
    And miles to go before I sleep.\n
    "
    )
    ->search("woods");
/* Returns: [
        "Whose woods these are I think I know.",
        "To watch his woods fill up with snow.",
        "The woods are lovely, dark and deep,",
    ]
*/

EloquentRegex::source(
    "
    Please contact us via email at [email protected] for more details.
    For support inquiries, you can also email us at [email protected].
    Our marketing team is reachable at [email protected] for collaborations.
    For urgent matters, you can reach out through the phone number provided.
    Subscribe to our newsletter to stay updated with the latest news.
    Feel free to send feedback directly to our office address.
    Any emails sent after 5 PM may be responded to the next business day.
    Check the FAQ section for answers to common questions.
    Social media channels are also available for quick updates.
    We value your input and encourage you to share your thoughts.
    "
    )
    ->search(function ($pattern) {
        $pattern->email();
    });
/* Returns:
[
    'Please contact us via email at [email protected] for more details.',
    'For support inquiries, you can also email us at [email protected].',
    'Our marketing team is reachable at [email protected] for collaborations.'
]
*/

/*
===========================================================
| ROWS | Find (row count)  | File size  | Find + decoded |
===========================================================
| 1000 | 7.6 ms (890)      | 5 Mb       | 11.5 ms        |
| 2500 | 17.25ms (2186)    | 14 Mb      | 30 ms          |
| 5000 | 34.4 ms (4347)    | 29 Mb      | 62 ms          |
| 10K  | 67.4 ms (8669)    | 58 Mb      | 112 ms         |
| 20K  | 131 ms (17313)    | 116 Mb     | 251 ms         |
===========================================================
===Keyword:="green"========================================
*/

// Find all logs types except INFO
EloquentRegex::source(
    "
    [2024-12-23 10:00:00] INFO: User logged in.\n
    [2024-12-25 10:05:00] ERROR: Unable to connect to database.\n
    [2024-12-25 10:10:00] INFO: User updated profile.\n
    [2024-12-15 10:15:00] WARNING: Disk space running low.\n
    [2024-12-34 10:20:00] ERROR: Timeout while fetching data.\n
    "
    )
    ->searchReverse("INFO");
/* Returns: [
        '[2024-12-25 10:05:00] ERROR: Unable to connect to database.',
        '[2024-12-15 10:15:00] WARNING: Disk space running low.',
        '[2024-12-34 10:20:00] ERROR: Timeout while fetching data.',
    ]
*/

$builder= EloquentRegex::start("URIs: /container-tbilisi-1585, /container-berlin-1234, /container-tbilisi-2555")
    ->slash() // "/"
    ->exact("container") // "container" (static part of URI)
    ->dash() // "-"
    ->namedGroup(function ($pattern) {
        return $pattern->text();
    }, "City") // Text between dashes, Grouped & named as "city"
    ->dash() // "-"
    ->namedGroup(function ($pattern) {
        return $pattern->digitsRange(2, 5);
    }, "id") // Numbers at end, Grouped & named as "id"
    ->end(); // Ends custom pattern to make "swap" method available

// Using swap with pattern string
// which will swap placeholders like "[ID]" with
// Extracted data for each found match
$builder->swap("/container/[ID]?city=[CITY]");

/* Returns:
[
    '/container/1585?city=tbilisi',
    '/container/1234?city=berlin',
    '/container/2555?city=tbilisi'
]
*/

$builder = EloquentRegex::start("Issues in progress: RI-2142, RI-1234, PO-2555");
$builder
    ->namedGroup(function ($pattern) {
        return $pattern->textUppercase(2);
    }, "project", 1) // 2 uppercase char named as "project"
    ->dash() // "-"
    ->namedGroup(function ($pattern) {
        return $pattern->digitsRange(2, 4);
    }, "issue", 1) // from 2 to 4 digits named as issue
    ->end();

    $results = $result->swap(function ($data) {
        return "The issue #" . $data["issue"] . " of project " . $data["project"] ." is in progress";
    });

/* Returns:
[
    'The issue #2142 of project RI is in progress',
    'The issue #1234 of project RI is in progress',
    'The issue #2555 of project PO is in progress'
]
*/

EloquentRegex::source($yourString);

EloquentRegex::source($yourString)->url();

// get() will return array/collection of URLs if any found in $yourString
EloquentRegex::source($yourString)->url()->get();

// check() will return true if $yourString exactly matches the pattern
// In this case, if $yourString is URL, false otherwise
EloquentRegex::source($yourString)->url()->check();

// checkString() will return true if $yourString contains any matches of the pattern
// In this case, if $yourString contains minimum 1 URL, false otherwise
EloquentRegex::source($yourString)->url()->checkString();

// count() will return count of matches, in this case, amount of URLs in $yourString
EloquentRegex::source($yourString)->url()->count();

// toRegex() will return string - raw regex pattern (without options applied)
EloquentRegex::source($yourString)->url()->toRegex();

public function textOrNumbers(
  int $minLength,
  int $maxLength,
  int $minUppercase,
  int $minLowercase,
  int $minNumbers,
  int $maxNumbers
);

// $onlyDomains & $onlyExtensions array
// or string separated by comma `"example.org,example.com"`
public function email(
  int $maxLength,
  array|string $onlyDomains,
  array|string $onlyExtensions
);

public function url(array|string $onlyProtocol);

// $onlyDomains & $onlyExtensions array or string separated by comma "org,com"
public function domainName(
  int $maxLength,
  array|string $onlyDomains,
  array|string $onlyExtensions
);

// Support YYYY-MM-DD, DD-MM-YY and DD-MM-YYYY formats with any date separator ("/", ".", "-")
public function date();

public function time();

public function ipAddress();

public function ipv6Address();

// $cardTypes string separated by comma "visa, amex"
public function creditCardNumber(string $cardTypes);

// $countryCode should passed without "+" sign: phone("1"), phone("995")
public function phone(string $countryCode);

public function username(int $maxLength);

public function password(
  int $minLength,
  int $minUppercase,
  int $minNumbers,
  int $minSpecialChars
);

// $restrictTags & $onlyTags array or string
// separated by comma `"script, style"`.
// It isn't recomended to use both option simultaneously
public function htmlTag(array|string $restrictTags, array|string $onlyTags);

// $specificCurrencies array of currency symbols or string separated by comma "$, ₾"
public function currency(
  int $minDigits,
  int $maxDigits,
  array|string $specificCurrencies
);

// $pathType allowed values: "absolute" & "relative"
public function filePath(
  int $isDirectory,
  bool $isFile,
  bool $fileExists,
  string $pathType
);

public function filePathWin(
  int $isDirectory,
  bool $isFile,
  bool $fileExists
);

EloquentRegex::start($yourString);
// Or
EloquentRegex::customPattern($yourString);

$result = EloquentRegex::start('ID123456')
            ->literal('ID')
            ->digitsRange(1, 10)
            ->check();

if ($result) {
    echo "The string matches the custom ID format!";
} else {
    echo "The string does not match the custom ID format.";
}


// Matches a string that may or may not contain a dash
$result = EloquentRegex::start($yourString)->exact("123")->dash('?')->exact("456")->check();
// Result would be true in both cases of $yourString: "123456" & "123-456"

// Matches a string with 2 to 5 spaces
$result = EloquentRegex::start($yourString)->text()->space('2,5')->digits()->check();
// Result: the "someText  234" would return true, but the "someText 234" false

// Matches strings with one or more backslashes
$result = EloquentRegex::start("\\\\")->backslash('1+')->check();
// Result: true (if one or more backslashes are found)

// Matches strings with zero or more forward slashes
$result = EloquentRegex::start($yourString)->alphanumeric()->dot('0+')->check();
// Result would be true in both cases of $yourString: "test258..." & "test"

// Matches strings with exactly 2 underscores
$result = EloquentRegex::start($yourString)->digits()->underscore('2')->digits()->check();
// Result would be true in cases $yourString: "1235__158", but "1235___158" and "1235_158" will be false


// Matches strings with exactly 3 periods or colons
$regex = EloquentRegex::builder()->start()
    ->charSet(function ($pattern) {
        $pattern->period()->colon();
    }, '3')->toRegex();
// Result: ([\.\:]){3}

// By defualt it is set as One or More
EloquentRegex::start($yourString)->digits();

// You can completly remove quantifier by passing 0 as first argument
EloquentRegex::start($yourString)->digits(0);

// You can specify exact amount of digit by passing int
EloquentRegex::start($yourString)->digits(5);

// You can specify range of digits by adding "Range" to the method
EloquentRegex::start($yourString)->digitsRange(1, 5); // Matches from 1 to 5 digits

EloquentRegex::source("StrongP@ssw0rd")->password(8, 1, 1, 1)->check();

EloquentRegex::source("StrongP@ssw0rd")->password(function($pattern) {
  $pattern->minLength(8)->minUppercase(1)->minNumbers(1)->minSpecialChars(1);
})->check();


EloquentRegex::source("StrongP@ssw0rd")
->password([
  "minLength" => 8,
  "minUppercase" => 1,
  "minNumbers" => 1,
  "minSpecialChars" => 1,
])->check();

// The "filePath" pattern matches any file path
// While "pathType" option Asserts the file path is an absolute
EloquentRegex::source("/var/www/html/index.php")
  ->filePath(["pathType" => "absolute"])
  ->check();

$string = "Visa: 4111 1111 1111 1111, MasterCard: 5500 0000 0000 0004, Amex: 3400 000000 00009";
// The "creditCardNumber" pattern matches any credit card number
// While "cardTypes" (#1 argument) option filters and returns only VISA and AMEX accordingly
$cards = EloquentRegex::source($string)->creditCardNumber("visa, amex")->get();

// example of using end() method with config array
EloquentRegex::customPattern("Users: user_123, JohnDoe_99")
  ->alphanumeric()
  ->underscore()
  ->digitsRange(0, 2)
  ->end(["minLength" => 10])
  ->checkString();

// example of using end() method with callback
$check = EloquentRegex::customPattern("Users: user_123, JohnDoe_99")
  ->alphanumeric()
  ->underscore()
  ->digits()
  ->end(function ($p) {
      $p->minLength(10)->maxDigits(2);
  })
  ->checkString();

public function minLength(int $minLength);
public function maxLength(int $maxLength);
public function length(int $exactLength);

public function minNumbers(int $minDigits);
public function maxNumbers(int $maxDigits);
public function minDigits(int $minDigits);
public function maxDigits(int $maxDigits);
public function numberAmount(int $exactAmountOfDigits);

public function onlyChars(array $characters);
public function excludeChars(array $characters);
public function minUppercase(int $minAmount);
public function minLowercase(int $maxAmount);
public function minSpecialChars(int $minAmount);
public function maxSpecialChars(int $maxAmount);
public function noSpecialChars(bool $disable = true);
public function onlyLowercase(bool $only = true);
public function onlyUppercase(bool $only = true);

public function validIPv6();

public function isFile(string|null $extension = null);
public function isDirectory(int $check = 1);

public function fileExists(bool $check = true);

public function specificCurrencies(array|string $currencies);
public function onlyUSD($only = true);
public function onlyEUR($only = true);
public function onlyGBP($only = true);
public function onlyGEL($only = true);

// Allowed values int 1; string "absolute" | int 2; string "relative";
public function pathType(string|int $value = 0);

public function countryCode(string $code);

public function noSpaces(bool $disallow = true);
public function noDoubleSpaces(bool $disallow = true);
public function maxSpaces(int $max);

public function onlyDomains(array|string $domains);
public function onlyExtensions(array|string $extensions);

public function onlyProtocol(string|array $protocol);
public function onlyHttp(bool $only = true);
public function onlyHttps(bool $only = true);

public function onlyVisa(bool $only = true);
public function onlyMasterCard(bool $only = true);
public function onlyAmex(bool $only = true);
public function cardTypes(string $cardTypes);

public function onlyAlphanumeric(bool $only = true);

public function onlyTags(array|string $tags);
public function restrictTags(array|string $tags);

// When $string can be "[email protected]", or "[email protected]", or "[email protected]" and etc.
$checkWithFlag = EloquentRegex::source($string)
                ->start()
                ->exact("example")
                ->character("@")
                ->exact("email.com")
                ->end()
                ->asCaseInsensitive()->check();

// With the case-insensitive flag, the match succeeds.
expect($checkWithFlag)->toBeTrue();

$string = "2024-01-30\n2024-02-15\n2024-11-30";
$matches = EloquentRegex::source($string)
            ->start()
            ->digits(4)->dash()
            ->digits(2)->dash()
            ->digits(2)
            ->end() // Here you can apply options
            ->asMultiline()->check();
expect($matches)->toBeTrue();

$string = "Check out\n this site:";
$check = EloquentRegex::source($string)
          ->start()->anyChars()->character(":")->end()->asSingleline()
          ->check();
expect($check)->toBeTrue(); // Matches across lines due to the single-line flag.


$string = "მზადაა #1 ✔️ და #2 ✔️";
$matches = EloquentRegex::source($string)
            ->start()->wordCharsRange(0, 2)->end()->asUnicode()->get();
expect($matches)->toContain('და'); // Matches Unicode characters with the Unicode flag.


// Matches exactly 3 occurrences of periods or colons
EloquentRegex::start(".:.")
->charSet(function ($pattern) {
    $pattern->period()->colon();
}, '3')->check();
// Expected to be true as it matches three instances of either a period or a colon

// Matches a string containing 2 to 4 characters that are not digits
EloquentRegex::start("abcd")
->negativeCharSet(function ($pattern) {
    // Here, quantifiers inside the set are interpreted as literal symbols
    // Character classes like "digits", "text", and etc. sets default quantifier (+)
    // Hence, '0' is used to disable automatic quantifier addition
    $pattern->digits(0);
}, '2,4')->check();
// Expected to be true as it matches between 2 to 4 non-digit characters

// Matching a date format with capturing the parts as separated groups
$result = EloquentRegex::start("2024-01-30, 2023-02-20")
->group(function($pattern) {
    $pattern->digits(4); // Year
})->dash()
->group(function($pattern) {
    $pattern->digits(2); // Month
})->dash()
->group(function($pattern) {
    $pattern->digits(2); // Day
})->end(["excludeChars" => ["4"]])
->get();

/**
 * After excluding "4" character, it filters out
 * the "2024-01-30" match and returns only "2023-02-20"
 * with it's capture groups, so that you get this array:
 * [
 *     [
 *          "result" => "2023-02-20",
 *          "groups" => [
 *              "2023",
 *              "02",
 *              "20"
 *          ],
 *     ]
 * ]
 */

// Matching a date format with capturing the parts as separated groups
EloquentRegex::start("RI-2142, PO-2555")
    ->namedGroup(function ($pattern) {
        return $pattern->textUppercase(2);
    }, "project", 1)
    ->dash()
    ->namedGroup(function ($pattern) {
        return $pattern->digitsRange(2, 4);
    }, "issue", 1)
    ->get();

/* Returns:
[
    "result" => "RI-2142",
    "groups" => [
        "project" => "RI",
        "issue" => "2142",
    ]
],
[
    "result" => "PO-2555",
    "groups" => [
        "project" => "PO",
        "issue" => "2555",
    ]
]
 */

// Reproduces an 'alt' html property pattern fron HSA
$regex = EloquentRegex::start('alt="something"')
    ->exact("alt=")
    ->nonCapturingGroup(function ($pattern) {
        $pattern->doubleQuote()->orPattern(function ($pattern) {
            $pattern->singleQuote();
        });
    })->check(); // True; Regex: alt\=(?:\"|')

EloquentRegex::start("345-45, 125-787, 344643")
  ->nonCapturingGroup(function ($pattern) {
    $pattern->digits()->dash()->digits();
  }, '+') // Using "+" to match One Or More of this group
  ->get();
// It returns array: ["345-45", "125-787"]

// Expected to be true as '3' is followed by 'D'
EloquentRegex::start('3D')
->digits()->lookAhead(function($pattern) {
    $pattern->character('D');
})->check();
// While using "get()" method, 'D' doesn't appear in matches

// Expected to be true as '3' is preceded by 'P'
EloquentRegex::start('P3')
->lookBehind(function($pattern) {
    $pattern->character('P');
})->digits()->check();
// While using "get()" method, 'P' doesn't appear in matches

// "3A" returns True
$string = "3A";
// "3-" returns False
$string = "3-";
EloquentRegex::start($string)
->digits()->negativeLookAhead(function($pattern) {
    $pattern->character('-');
})->check();
// While using "get()" method, '-' doesn't appear in matches

// "A3" returns True
$string = "A3";
// "-3" returns False
$string = "-3";
EloquentRegex::start($string)
->negativeLookBehind(function($pattern) {
    $pattern->character('-');
})->digits()->check();
// While using "get()" method, '-' doesn't appear in matches

EloquentRegex::builder()->start()
    ->exact("alt=")
    ->group(function ($pattern) {
        $pattern->doubleQuote()
        ->orPattern(function ($pattern) {
            $pattern->singleQuote();
        });
    })->toRegex(); // alt\=(\"|')

// Directly adds a raw regex pattern for an SSN
EloquentRegex::start('123-45-6789')
    ->addRawRegex('\d{3}-\d{2}-\d{4}')
    ->check();
// Expected to match an SSN format '123-45-6789', but not '123456789'

// Wraps digits in a non-capturing group and expects an 'A' immediately after
EloquentRegex::source('123A')
    ->addRawNonCapturingGroup('\d', "oneOrMore")->exact('A')
    ->check();
// Expected to match '123A' but not 'A123'

$text = "Normal text {secret: message one} more text {secret: another hidden text} end";
$matches = EloquentRegex::source($text)
    ->lookBehind(function ($pattern) {
        $pattern->openCurlyBrace()->exact('secret: ');
    })
    ->lazy()->anyChars()
    ->lookAhead(function ($pattern) {
        $pattern->closeCurlyBrace();
    })
    ->get();

// Extracts ['message one', 'another hidden text'] as separate matches

$pattern = EloquentRegex::source('your test string here')
    ->start()
    ->wordChars()->whitespace()->digits()
    ->end()
    ->toRegex();

// Now, $pattern contains the raw regex string that you can test or debug further.

use Maestroerror\EloquentRegex\EloquentRegex;

$isValid = EloquentRegex::source('[email protected]')->email()->check();

$result = EloquentRegex::start('user_123')
->alphanumeric()
->underscore()
->digits()
->get();