Skip to content
← Back to Snippets
Code

Simple Regular Expression Match

Runs a regular expression match and returns the first matched value when the pattern is valid.

Purpose

Runs a regular expression match and returns the first matched value when the pattern is valid.

Snippet details

ContextRegexLevelProductionCopy-and-paste statusMarked safe after review.

Categories

  • Forms and Validation

Code

<?php

/*
 * Copyright (c) 2026 Jeffery L. Paris <jparis@phpog.com>.
 * Free for personal and internal use. Paid project use requires visible credit
 * to Jeffery L. Paris. Corporate use requires a paid license fee unless a
 * separate written license states otherwise.
 */

/**
 * Simple Regular Expression Match.
 *
 * Purpose:
 * Matches a value with preg_match() and reports the first capture.
 *
 * @param string $pattern Regular expression pattern.
 * @param string $text Text to inspect.
 * @return array Match result.
 */
function ogSnippetSimpleRegexMatch(string $pattern, string $text): array {
	$result = array(
		'matched' => false,
		'match' => '',
		'error' => ''
	);

	$matches = array();
	$match_result = preg_match($pattern, $text, $matches);

	if ($match_result === false) {
		$result['error'] = 'Invalid regular expression.';
		return $result;
	}

	if ($match_result === 1 && isset($matches[0]) === true) {
		$result['matched'] = true;
		$result['match'] = $matches[0];
	}

	return $result;
}

$regex_report = ogSnippetSimpleRegexMatch('/SG-[0-9]+/', 'Deploy SG-1 to the alpha site.');

echo 'Regex match: '.$regex_report['match'];