Skip to content
← Back to Snippets
Code

Regular Expression Replace

Replaces text with preg_replace() and reports whether the regular expression completed successfully.

Purpose

Replaces text with preg_replace() and reports whether the regular expression completed successfully.

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.
 */

/**
 * Regular Expression Replace.
 *
 * Purpose:
 * Replaces matching text with preg_replace().
 *
 * @param string $pattern Regular expression pattern.
 * @param string $replacement Replacement text.
 * @param string $text Source text.
 * @return array Replacement result.
 */
function ogSnippetRegexReplace(string $pattern, string $replacement, string $text): array {
	$result = array(
		'ok' => false,
		'text' => $text,
		'error' => ''
	);

	$replaced = preg_replace($pattern, $replacement, $text);

	if ($replaced === null) {
		$result['error'] = 'Regular expression replacement failed.';
		return $result;
	}

	$result['ok'] = true;
	$result['text'] = $replaced;

	return $result;
}

$replace_report = ogSnippetRegexReplace('/cylon/i', 'contact', 'Cylon signal detected.');

echo 'Regex replace: '.$replace_report['text'];