Build A Regular Expression Tester With Laravel

Build A Regular Expression Tester With Laravel

In the last episode we built a bare bones regular expression tester using PHP. It does what we need it to, but its really limited, and doesn’t look that great. In this episode, we are going to Larafy it. We’re going to re build the regular expression tester using Laravel. This should be a good test of hacking something quick and dirty together using native PHP versus building it in a framework like Laravel. The two approaches are really different, and this little exercise will give us a good idea of how to change up our thinking. Let’s check it out.

Laravel 4.2

For this example, we’re going to make use of Laravel 4.2. Though we’re all looking forward to Laravel 5 and all of the cool new features it has – it still is a moving target as things change so we’ll stick with Laravel 4.2 for now. We’re going to mimic what we did in the first iteration of this project without a framework. This is the first iteration with Laravel, and I’m taking the approach of simply, get something working, then worry about refactoring later. So that is what we’ll do.



Route::get('/', function () {
    $result = Session::get('result');
    $message = Session::get('message');
    return View::make('regex')->with(['result' => $result, 'message' => $message]);

Route::post('regex', function () {
    $data = Input::all();

    $validation = Validator::make($data, ['subject' => 'required', 'pattern' => 'required']);
    if ($validation->fails()) {
        return Redirect::to('/')->withInput()->withErrors($validation);

    $subject = $data['subject'];
    $pattern = $data['pattern'];

    try {
        preg_match_all('/' . $pattern . '/', $subject, $matches);
    } catch (Exception $e) {
        return Redirect::to('/')->withInput()->with('message', $e->getMessage());

    if (sizeof($matches[0]) > 0) {
        foreach ($matches[0] as $match) {
            $result[] = $match;
        Session::flash('result', $result);
    } else {
        Session::flash('message', 'There were no matches');
    return Redirect::to('/')->withInput();


<!doctype html>


    <script src=""></script>
    <link rel="stylesheet" href="//">
    <script src="//"></script>
    <meta charset="utf-8">
    <title>Regex Test</title>

<div class="container">
        <h1>Laravel Regex Tester</h1>

        <p class="lead">Test a regex.</p>
    <div class="row">
        <div class="col-sm-8 blog-main"> @yield('content') </div>




    {{ Form::open( ['url' => 'regex'] ) }}

    {{ Form::label('subject', 'Enter the haystack here.') }}
    {{ Form::textarea('subject', '', ['class' => 'form-control']) }}
    {{  $errors->first('subject', '<div class="alert alert-danger"><b>:message</b></div>')  }}
    {{ Form::label('pattern', 'Enter your regex patter here.') }}
    {{ Form::text('pattern', '', ['class' => 'form-control']) }}
    {{  $errors->first('pattern', '<div class="alert alert-danger"><b>:message</b></div>')  }}
    {{ Form::submit('Preg Match All', ['class' => 'btn btn-info']) }}

    {{ Form::close() }}

    @if(sizeof($result[0]) > 0)
        <div class="alert alert-success">Here are your matches</div>
        @foreach( $result as $match )
            {{ $match }} <br>
        @if(strstr($message,'Here are your matches'))
            <div class="alert alert-info"> {{ $message  }} </div>
            <div class="alert alert-danger"> {{ $message  }} </div>

These three files make up the application. Let’s test it out.

Visiting The App For The First Time

First up, we just want to make sure that when we visit the regular expression tester, that it loads properly and we don’t get any random errors or messages that shouldn’t be there. We visit http://localhost/laravel/public/ and all looks well.
laravel regular expression tester

Submitting A Regex Test With No Pattern

We test the validation by submitting a test without filling in the regex pattern. We see the validation working great, as we get the error message as shown here.
laravel regex validation

Submitting A Regex Test With No Subject

Testing the form without including a subject shows validation working here as well.
laravel regex validation two

Example of Successful Regex Matches

Now that we see how the basic validation is working, lets test out some actual regex matching with a valid subject and pattern. We can see that by submitting our test, we get a nice flash message back with the number of matches each on a new line. In this case we matched ‘Laravel’ and found two matches. Cool!
laravel regular expression successful match

What Happens When There Are No Matches?

We need to account for when there are no matches for our regular expression test. This is built in and we can test this out now. What’s nice is that we can leave our test string in place in the subject text area, since we have the application set up to repopulate the form on each iteration. Our current string of ‘This is some example text about Laravel and we’ll match Laravel with a regular expression now.’ has no numbers, so lets’ try to match a number with a regular expression to see how the app handles this. We can see that when trying to match a digit, we get a nice error message like so.
laravel regular expressions no matches

Catching Exceptions in our Little Laravel App

There will be instances when we provide a pattern to the application that is not understood by the preg_match_all function under the hood. In those cases, we want to catch the exception that gets thrown, and display it in a nice way. Otherwise, we’ll get the usual ugly failures that we see when PHP fails on a script. Due to the try catch sequence we included in the logic, this works out pretty good as well. In this example we can see a message of preg_match_all(): Unknown modifier ‘d’.
regex catch exceptions


This was a fun little test of hacking together a quick and dirty regular expression tester in Laravel. We made use of basic routes, Laravel Blade templating, Laravel Validation, and some good old fashioned native PHP to accomplish our goal. Thanks for checking it out.