Download the PHP package maestroerror/eloquent-regex without Composer

On this page you can find all versions of the php package maestroerror/eloquent-regex. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.

FAQ

After the download, you have to make one include require_once('vendor/autoload.php');. After that you have to import the classes with use statements.

Example:
If you use only one package a project is not needed. But if you use more then one package, without a project it is not possible to import the classes with use statements.

In general, it is recommended to use always a project to download your libraries. In an application normally there is more than one library needed.
Some PHP packages are not free to download and because of that hosted in private repositories. In this case some credentials are needed to access such packages. Please use the auth.json textarea to insert credentials, if a package is coming from a private repository. You can look here for more information.

  • Some hosting areas are not accessible by a terminal or SSH. Then it is not possible to use Composer.
  • To use Composer is sometimes complicated. Especially for beginners.
  • Composer needs much resources. Sometimes they are not available on a simple webspace.
  • If you are using private repositories you don't need to share your credentials. You can set up everything on our site and then you provide a simple download link to your team member.
  • Simplify your Composer build process. Use our own command line tool to download the vendor folder as binary. This makes your build process faster and you don't need to expose your credentials for private repositories.
Please rate this library. Is it a good library?

Informations about the package eloquent-regex

eloquent-regex

EloquentRegex brings the simplicity and elegance to regular expressions. Designed for Laravel developers, this package offers a fluent, intuitive interface for building and executing regex patterns in your PHP applications.

Like what we're doing? Show your support with a quick star, please! ⭐

Want the same power directly in the browser? Check out the JS version: SimplifiedRegex 🚀

Feeling overwhelmed by the documentation? With a ChatGPT Plus subscription, you can streamline your experience by utilizing the EloquentRegex Assistant GPT 🤖

Table of Contents

Overview

Dreaming of a world where regex doesn't feel like a rocket science? 😄🚀

Regular expressions (regex) are powerful, no doubt. They're the Swiss Army knife for string manipulation and validation. But let's be honest, they can also be a bit of a headache. The syntax is dense, and a tiny mistake can throw everything off. It's like they're designed to be as intimidating as possible, especially when you're just trying to validate an email address!

Enter EloquentRegex. Our goal is to make working with regex in Laravel not just bearable, but actually enjoyable. Yes, you heard that right—enjoyable!

EloquentRegex is a PHP/Laravel package that offers a fluent, intuitive interface for constructing and executing regular expressions. Whether you need to validate user input, parse text, or extract specific information from strings, EloquentRegex makes it simple and straightforward.

For example:

Another:

One more 😄

Key Features🔑

For more details about package and it's inner workings check out STRUCTURE.md file.

Getting Started🧭

Simply install the package via Composer, and you're ready to take the pain out of regex in your PHP/Laravel applications. Run for installation:

Remember, regex doesn't have to be a source of frustration. With EloquentRegex, you're on your way to becoming a regex master, all while writing cleaner, more maintainable Laravel code.

Need to get started quickly? Read the quick start guide! 🚀

Basic Usage

EloquentRegex simplifies regular expressions in Laravel, making it easy to validate data, search text, and extract information. This section introduces the basic usage of EloquentRegex, including leveraging ready-to-use patterns and creating custom patterns.

First of all, you need to include EloquentRegex class.

Recomended for Laravel:

Usage structure is very similar to Laravel's Eloquent ORM, check this out:

Let's break it down:

Note: ?Optional methods mostly are the expression flags, we will talk about them in next sections

Ready-to-Use Patterns📑

EloquentRegex comes with a set of predefined patterns for common validation/extraction tasks. These patterns are designed to be straightforward and easy to use, requiring minimal effort to implement.

We have different ways to apply options, but the most common and easy way is to pass them as arguments. Note that all arguments are optional.

Here you can check all available methods of ready-to-use patterns and their arguments:

Didn't it cover all your needs? Let's take a look to the custom patterns section.

Custom Patterns🛠️

For scenarios where predefined patterns do not suffice, EloquentRegex allows you to define custom patterns using the start or customPattern methods as initiator:

Note: They does the exaclty same thing, you can use your favorite one

Creating a Custom Pattern

You can start building a custom pattern to match a specific string format, such as a custom ID format that starts with letters followed by digits:

Note: You can use EloquentRegex::builder()->pattern() if you need just build a regex without source string

Custom pattern builder supports a wide range of character classes and all special chars. Also, literal or exact method could be used to match exact string you need, or char method could be used to match exact character. The full list of pattern builder methods is comming soon. Before that, you can check this files out:

Applying Quantifiers#️⃣

Quantifiers in regular expressions are symbols or sets of symbols that specify how many instances of a character, group, or character class must be present in the input for a match to be found. EloquentRegex enhances the way quantifiers are used, making it simpler and more intuitive to define the frequency of pattern occurrences.

Optional Elements

To make an element optional, use '?'. This matches zero or one occurrence of the preceding element (dash in this example).

Specifying a Range

For specifying a range of occurrences, use a string with two numbers separated by a comma '2,5'. This matches the preceding element at least and at most the specified times.

One or More

To match one or more occurrences of an element, use '+', '1+', '1>' or 'oneOrMore'. This ensures the element appears at least once.

Zero or More

The '0+' quantifier matches zero or more occurrences of the preceding element.

Exact Number

To match an exact number of occurrences, directly specify the number.

To Custom Character Sets and groups

You can apply quantifiers to custom character sets and groups as second argument after the callback, matching a specific number of occurrences.

Quantifier values

In Special characters and Groups - nearly all methods allowing quantifiers with values:

Example: ->literal("hello world", false, "1+")

But Character Classes have different approach, lets take digits as example:

Advanced usage

As you become more comfortable with the basics of EloquentRegex, you might find yourself needing to tackle more complex string manipulation challenges. The "Advanced Usage" section is designed to take your skills to the next level.

Whether you're dealing with intricate string formats, dynamic pattern requirements, or simply looking to optimize your regex operations for performance and clarity, this section will guide you through the advanced features of EloquentRegex. You'll learn how to leverage the full power of this package to make your Laravel application's text processing as efficient and effective as possible.

Options⚙️

EloquentRegex provides a flexible system for applying options to your patterns. These options can serve as extra assertions to refine pattern matching or act as filters to select only specific matches. There are three main ways to apply options: directly as arguments, through a callback, and via an associative array.

Direct Arguments

Pass options directly as arguments to pattern methods for straightforward use cases.

Callback

A callback offers the most flexibility, allowing any option to be applied to any pattern. Also, It's the recommended approach for complex configurations to keep your code simple and readible.

Associative Array

Options can also be specified using an associative array, providing a clear and concise way to configure multiple options at once.

Note: To keep it simple - all option methods have exactly one argument

Options as extra assertions

Options can make extra assertions (while using check or checkString methods) beyond the basic pattern match, ensuring that matches meet specific criteria.

Options as filters

In some cases (While using get method), options serve to filter the results obtained from a pattern match, allowing only certain matches to pass through.

Options in custom patterns

Using custom pattern is greate way to cover specific use cases, but there can be a moment when you need extra assertion or filter for you matches. While the end() method if optional by default, if you need to apply the Options to yor custom pattern, you should pass array or callback to the end() method:

Options list

Below is a list of all available options for now. As previously mentioned, options can be applied to any pattern using either a callback or an array.

While this flexibility allows you to tailor your regex patterns precisely, it's important to understand that some options more specific and some are more global in terms of appliance. Choosing the right option depends on the specifics of your use case.

I grouped options by the classes behind them to make their purpose more clear:

Note: Options having default value can be used without arguments (noSpecialChars()) in callback, but it needs argument while using array ["noSpecialChars" => true]

Regex Flags🚩

Regex flags are special tokens that modify the behavior of regular expressions, allowing for more flexible and powerful pattern matching. In EloquentRegex, applying regex flags to your patterns enables specialized matching behaviors such as case-insensitive searches, multiline matching, single-line mode, and support for Unicode characters. Let's explore how to apply these flags using examples.

Case-Insensitive Matching

Sometimes, the case of letters in a string should not affect the match. To achieve case-insensitive matching, use the asCaseInsensitive() flag.

Multiline Matching

The multiline flag allows the start (^) and end ($) anchors to match the start and end of lines within a string, rather than the entire string.

Example: Matching Dates Across Multiple Lines using check() method

Note: if you need to check if string contains a date, using checkString() method is enough. In this example we are checking that every line is exactly the date.

Single-Line Mode

In single-line mode, the dot (.) matches every character, including newline characters, allowing patterns to match across lines.

Example: Matching Text Across Lines as a Single Line String using check() method

Unicode Character Matching

When working with texts containing Unicode characters, the Unicode flag ensures that character classes such as \w (word characters - wordChars method) and \d (digits - digits method) correctly match Unicode characters.

Example: Matching Text with Unicode Characters

Advanced builderPattern methods

In addition to character classes and special character methods, builderPattern has more advanced methods for increasing flexibility and usage scope. Below are described the methods for the builderPattern's advanced usage.

Character Sets🗃️

In regular expressions, character sets are a fundamental concept that allows you to define a set of characters to match within a single position in the input string. EloquentRegex provides an intuitive way to work with both positive and negative character sets, enhancing the versatility of your patterns.

Positive set (only these characters)

A positive character set matches any one of the characters included within the set. It's specified by enclosing the characters in square brackets [...].

Example: Matching a Specific Number of Character Sets

In this example, the character set [\.\:] is created to match either a period . or a colon : (In charSet order of characters not matter). The quantifier '3' is applied outside the set to match exactly three occurrences of any of these characters.

Negative set (all but not these characters)

A negative character set, denoted by [^...], matches any character that is not listed within the brackets.

Example: Matching a Specific Number of Negative Character Sets

Note about character classes

When working with character sets in EloquentRegex, it's important to remember that quantifiers are not allowed inside the set itself because they will be interpreted as symbols. To include character classes like "\d" for digits within a set without applying a quantifier to the class itself, you should pass 0 as the first argument where quantifier application is an option. This ensures that the character class is included in the set as intended, without unintended quantification.

Update: From now, 0 as argument is optional, because character classes willn't add default "+" quantifier inside the set

Groups📦

EloquentRegex simplifies the process of creating both capturing and non-capturing groups, allowing you to organize your regex patterns into logical sections and apply quantifiers or assertions to these groups as a whole.

Capturing Groups

Capturing groups are used to group part of a pattern together and capture the matching text for later use. Note that it returs array/collection with different structure while using with get:

Non-Capturing Groups

Non-capturing groups organize patterns logically without capturing separately the matched text.

Groups with quantifier

Both group methods are supporting quantifier as second argument. Quantifiers can be applied with exact same logic as described in Applying Quantifiers section.

Conditional matching❓

Assertion groups allow for conditional matching based on the presence (positive) or absence (negative) of patterns ahead or behind the current match point, without consuming characters from the string, so that anything inside assertion group willn't be added in matches. See examples below:

Positive Lookahead and Lookbehind Assertions

Example: Using lookAhead Assertions

Matches digits only if they are followed by a 'D'

Example: Using lookBehind Assertions

Matches digits only if they are preceded by a 'P'

Negative negativeLookAhead and Lookbehind Assertions

Matches digits only if they aren't followed by a '-'

Example: Using negativeLookBehind Assertions

Matches digits only if they aren't preceded by a '-'

Pattern alternation (orPattern)⚖️

Sometimes, you might encounter situations where either one pattern or another is acceptable. For instance, when developing EloquentRegex, a key objective was to enable the reproduction of patterns commonly used in HSA. Consider the alt attribute within an HTML tag, which can be followed by either a double " or a single ' quote. This requirement translates into a regex pattern like alt\=(\"|'), indicating an exact match for "alt=" followed by either type of quotation mark.

To achieve this with EloquentRegex, you can utilize the orPattern method:

In this example, we precisely match "alt=" using the exact method. We then create a group with the group method and include doubleQuote in group and then singleQuote within the orPattern method's callback. This approach ensures the pattern matches either " or '.

The orPattern method also accepts a quantifier as its second argument (after callback), applying the same quantifier logic as elsewhere in EloquentRegex. This feature adds another layer of flexibility, allowing you to specify how many times either pattern should be present.

Raw Methods🧩

When working with regular expressions, there are times you'll need to insert a segment of raw regex directly into your pattern. This might be due to the complexity of the pattern or simply because you're integrating an existing regex snippet. EloquentRegex accommodates this need with specific methods designed to seamlessly integrate raw regex patterns into your larger expressions.

Adding Raw Regex Patterns

The addRawRegex method allows you to insert any raw regex directly into your pattern. This is particularly useful for incorporating standard regex snippets without modification.

Example: Matching a Social Security Number (SSN)

This method is straightforward and ensures that your EloquentRegex pattern can accommodate complex requirements with ease.

Wrapping Raw Regex in a Non-Capturing Group

Sometimes, you may want to include a raw regex snippet as part of a larger pattern without capturing its match. The addRawNonCapturingGroup method wraps the provided raw regex in a non-capturing group, allowing it to participate in the match without affecting the captured groups.

Example: Adding Digits Followed by a Specific Letter

The Lazy Quantifier Method🐌

In the world of regular expressions, greediness refers to the tendency of quantifiers to match as much of the input as possible. However, there are scenarios where you want your pattern to match the smallest possible part of the input that satisfies the pattern, a behavior known as "laziness" or "non-greediness". EloquentRegex introduces a straightforward way to apply this concept through the lazy() method.

How the Lazy Method Works

The lazy() method modifies the behavior of quantifiers that follow it in the pattern, making them match as few characters as possible. This is particularly useful when you want to extract specific segments from a larger block of text without capturing unnecessary parts.

Example: Extracting "Secret Coded" Messages from Text

Consider a situation where you need to extract coded messages enclosed in curly braces and preceded by a specific keyword within a larger text. Using the greedy approach might lead to capturing more text than intended, including text between messages. The lazy() method ensures that only the content directly within the braces, following the keyword, is matched.

In this example, without the lazy() method, the pattern might greedily match from the first {secret: to the last }, including everything in between as a single match (message one} more text {secret: another hidden text). By applying lazy(), the pattern instead matches the smallest possible string that satisfies the pattern within each set of curly braces, effectively separating the messages.

When to Use the Lazy Method

The lazy() method is invaluable when dealing with patterns that include variable-length content, such as strings or blocks of text, where you aim to extract specific, bounded segments. It's especially useful in parsing structured formats embedded within free text, extracting data from templated content, or any scenario where precision is key to separating multiple matches in a larger string.

By making quantifiers lazy, EloquentRegex empowers you to write more precise and effective patterns, ensuring that your matches are exactly as intended, no more and no less.

Testing and Debugging Your Regex Patterns

Crafting the perfect regex pattern is an art that often requires iteration, testing, and debugging. EloquentRegex provides tools that make this process easier and more intuitive, allowing you to refine your patterns until they match precisely what you need. One of the most useful methods for this purpose is toRegex(), which outputs the raw regex pattern. Combined with online tools like Regexr, you can visualize and debug your patterns in a user-friendly environment.

Using the "toRegex" Method

The toRegex() method converts your EloquentRegex pattern into a standard regex pattern string. This is particularly useful for debugging purposes or when you need to share your pattern with others who might not be using EloquentRegex.

Example: Converting an EloquentRegex Custom Pattern to Raw Regex

Note: toRegex doesn't return regex patterns used by the Options

Debugging with Regexr

Regexr is a free online tool that allows you to test and debug regex patterns in real-time. It provides a detailed explanation of each part of your regex, matches highlighted in the text, and even a reference guide for regex syntax.

How to Use Regexr for Debugging:
  1. Convert Your Pattern: Use the toRegex() method to convert your EloquentRegex pattern into a raw regex string.
  2. Open Regexr: Go to https://regexr.com/ in your web browser.
  3. Paste Your Pattern: Paste the raw regex string into the "Expression" field on Regexr.
  4. Test Your Pattern: Enter test strings in the "Test String" area to see how your pattern matches. Regexr will highlight matches and provide useful insights and errors if the pattern doesn't work as expected.

Note: For debuging get method, open "Flags" dropdown and mark "global"

Tips for Effective Debugging

Testing and debugging are critical steps in ensuring your regex patterns do exactly what you intend. By leveraging the toRegex() method and tools like Regexr, you can make this process more manageable and efficient, leading to more accurate and reliable regex implementations in your Laravel applications.

Contributing to EloquentRegex

We welcome contributions from the community! Whether you're fixing bugs, adding new features, or improving documentation, your help makes EloquentRegex even better for everyone. We follow the classic GitHub contribution flow. Below is how you can get involved.

Note: Checking STRUCTURE.md out may help you understand the package better 👍

Getting Started

  1. Fork the Repository: Start by forking the EloquentRegex repository to your own GitHub account. This creates a personal copy for you to experiment with.

  2. Clone Your Fork: Clone your forked repository to your local machine to start making changes. Use the following command, replacing YOUR_USERNAME with your GitHub username:

  3. Set Up Your Environment: Make sure you have a working Laravel environment to test your changes against. Follow the setup instructions in the project README to get started.

Making Changes

  1. Create a New Branch: For each set of changes or new feature, create a new branch in your local repository. This keeps your work organized and separate from the main codebase.

  2. Make Your Changes: Implement your fixes, features, or documentation updates. Keep your changes focused and contained to the issue at hand for easier review.

  3. Commit Your Changes: Once you're satisfied with your work, commit the changes to your branch. Write clear, concise commit messages that explain the changes made.

  4. Push to Your Fork: Push your branch and changes to your fork on GitHub.

Submitting a Pull Request

  1. Pull Request (PR): Navigate to the original EloquentRegex repository on GitHub. You'll see an option to "Compare & pull request" for your branch. Click it to begin the process of submitting a PR.

  2. Describe Your Changes: Provide a detailed description of the changes in the PR. Include any relevant issue numbers. Explaining the reasoning behind the changes and how they improve EloquentRegex will help reviewers understand your contribution.

  3. Submit for Review: Once your PR is ready and all checks pass, submit it for review. At least one review from the project maintainers is required for merging. Be open to feedback and ready to make further tweaks based on suggestions.

Review and Merge

Check Out STRUCTURE.md

For more detailed information on the project structure and guidelines for contributing, please refer to the STRUCTURE.md file in the repository. It outlines the architecture of EloquentRegex and provides insights into naming conventions, file organization, and other best practices.

Thank you for considering contributing to EloquentRegex! Your efforts help improve the tool for developers everywhere ❤️.

Support

Support Our Work? 🌟 You can help us keep the code flowing by making a small donation. Every bit of support goes a long way in maintaining and improving our open-source contributions. Click the button below to contribute. Thank you for your generosity!

Or use QR code:

Credits

A project like EloquentRegex doesn't come to life in isolation. It's the result of inspiration, assistance, and support from various tools and communities. We would like to extend our heartfelt thanks to the following:

A special thank you goes out to everyone who has contributed to these tools and resources. Your work has not only aided in the development of EloquentRegex but has also contributed to the broader developer community by providing tools and knowledge that empower us all.

Frequently Asked Questions (FAQ)

What is EloquentRegex?

EloquentRegex is a PHP/Laravel package designed to simplify the creation and execution of regular expressions. It offers a fluent, intuitive interface for both building custom regex patterns and utilizing ready-to-use patterns for common tasks like email and URL validation.

How do I install EloquentRegex?

EloquentRegex can be installed via Composer. Run the following command in your Laravel project directory:

Can I use EloquentRegex without Laravel?

While EloquentRegex is specifically designed with Laravel in mind, the core functionality can be used in any PHP project via Maestroerror\EloquentRegex\EloquentRegex object with the same syntax.

How do I use ready-to-use patterns?

Ready-to-use patterns can be invoked by calling the corresponding method on the EloquentRegex class. For example, to validate an email address:

How do I create custom patterns?

Custom patterns can be created using the start or customPattern method. From there, you can chain methods to build your pattern:

Can I apply options to any pattern?

Yes, any options can be applied to any pattern using either a callback function or an associative array. This allows for flexible configuration of your regex patterns. Also, direct arguments to the pattern methods are used as extra, easy-to-use way for applying options.

How do I debug my regex patterns?

You can use the toRegex() method to get the raw regex pattern string. This can then be tested and debugged using online tools like Regexr, which provides real-time matching and detailed explanations. Check the Testing and Debugging section for more information.

How can I contribute to EloquentRegex?

Contributions are welcome! You can contribute by forking the GitHub repository, making your changes, and submitting a pull request. Please ensure your contributions adhere to the project's coding standards and guidelines.

Where can I report issues or request features?

Issues and feature requests can be submitted on the GitHub repository's Issues page. Please provide as much detail as possible to help us understand and address your request efficiently.

How do I stay updated on EloquentRegex developments?

To stay updated, follow the GitHub repository for the latest changes, releases, and discussions. You can also watch the repository to receive notifications for all project activities or follow the author's page.


To Do
Coming next

All versions of eloquent-regex with dependencies

PHP Build Version
Package Version
No informations.
Composer command for our command line client (download client) This client runs in each environment. You don't need a specific PHP version etc. The first 20 API calls are free. Standard composer command

The package maestroerror/eloquent-regex contains the following files

Loading the files please wait ....