Skip to content

One line preg_match for PHP

For a project I’ve been working on I needed to use preg_match quite a bit. But I got really tired of having to punch in several lines, so I cooked up this little snippet to pull out a specific match group.

<?php
/**
 * Shortcut to doing regex without needing to worry about $matches
 * @param type $pattern
 * @param type $search
 * @param type $group
 */
function preg_search($pattern, $search, $group=1) {
    if (preg_match($pattern, $search, $matches)) {
        if (isset($matches[$group])) {
            return $matches[$group];
        }
        return false; 
    }
    return false; 
}

$pattern and $search work just like normal preg_match. The $group parameter tells it which matching group to return, if it exists. If it doesn’t exist, it returns false.

Published inCode Tips

Be First to Comment

Leave a Reply

Your email address will not be published. Required fields are marked *