Regular Expressions made easy

By Jean Hertel, 24/02/2017, in category Tips

clean code, php, regular expression

Regular expressions are very common in the programming world. Every beginner to advanced programmer has already had to write some or attempt maintenance.

I confess that whenever I need to use regular expressions, be it to build something or give maintenance, I shudder. Maybe this happens because I understand little the running of regular expressions. Maybe it's because I've already see really big and complex expressions.

You will hardly spend your life on programming without using regular expressions, and therefore a simpler solution for writing them is necessary. If you do a search on the internet you will notice that there are several softwares to aid in the understanding and writing of regular expressions, but none of them solves a key problem: code maintenance.

A very elegant way of solving this problem is by using a library to construct expressions. Obviously reverting a regular expression is not a simple thing, but we can greatly improve its reading if we have a library that allows us to visually understand what this expression does.

Then comes Flux, a library that does this hard work of constructing expressions and keeping the code easy to maintain.

To install with composer use the command:

composer require selvinortiz/flux

After installing the dependency we can use as follows:

<?php
require __DIR__ . '/vendor/autoload.php';
$flux   = Flux::getInstance()
        ->startOfLine()
        ->find('http')
        ->maybe('s')
        ->then('://')
        ->maybe('www.')
        ->anythingBut('.')
        ->either('.co', '.com')
        ->ignoreCase()
        ->endOfLine();

To see the generated expression:

<?php
Helper::msg( $flux );

You can also test the regular expression directly with the library:

<?php
if($flux->match( "http://minhaUrl.com" )) {
    echo "Deu certo :)";
}

Official library site: https://github.com/selvinortiz/flux