Add to Favorites

Save time on form programming with regex

At times we all must create some more complex and lengthy html forms to capture data from our users. The process usually entails building out the design for the form then coding the form to HTML so they are usable. After the form is programmed, it is all nice and pretty but still does not perform any actual functionality. We then need to create the programming that sits behind the form to accept the form post and do something with the data ( capture to database, perform calculations, email data to administrator, etc ).

When you program the backend programming for the form, you usually need a list of the posting form variables so the programming knows what fields are being posted and can do validation or handle the data accordingly. Lets say you want an array of all the field names, so you can perform operations on them using php with the power of loops instead of manual labor. Instead of tediously copying all the field names and creating the array by hand, lets have php and regex do the work.

Here is a little script I wrote, that does just that. Use the page, submit a block of form html with a regex to match and it will pull out all matching elements to an array for you. If it matched too many items, it is easier for you to remove from the array then to build it by hand. Give it a try

<?php
if ( ! empty($_POST['text']) && ! empty($_POST['regex']) ) {
        $matches = array();
        preg_match_all($_POST['regex'],$_POST['text'],$matches);
        $keys = array();
        if ( $matches && count($matches) == 2 ) {
            echo '<pre>';
            foreach($matches[1] as $m) {
                if ( array_key_exists($m,$keys) ) echo $m .' is a duplicate' ."\n";
                $keys[$m] = '';
            }
            echo 'count ',count($keys),"\n";
            var_export($keys);
        }
    } else {
        $def_regex = '/name="(.*?)"/';
?>
    <form method="post">
        regex <input type="text" name="regex"
                 value="<?php echo htmlspecialchars($def_regex); ?>" /><br />
        <textarea name="text" style="width: 100%; height: 300px;"></textarea>
        <br />
        <input type="submit" value="Submit" />
    </form>
<?php
    }

when I run the form from the script above through the script itself, I get a lovely array that I can use. 

 array (
 'regex' => '',
 'text' => '',
 )

I usually take this array, and use it for validation rules for each field and run it through a validation function to check the rules.

 
$req = array (   'email_address' => 'email',   'name' => 'not_blank', )
$errors = validate_fields($_POST,$req); // custom function to validate array of field names
 
 

Comments

Be the first to leave a comment on this post.

Leave a comment

To leave a comment, please log in / sign up