Replace Text in a String
Replaces one text fragment with another and reports how many replacements were made.
Purpose
Replaces one text fragment with another and reports how many replacements were made.
Snippet details
ContextStringLevelProductionCopy-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.
*/
/**
* Replace Text in a String.
*
* Purpose:
* Replaces an exact text fragment and returns the changed text plus count.
*
* @param string $text Source text.
* @param string $search Text to find.
* @param string $replace Replacement text.
* @return array Replacement result.
*/
function ogSnippetReplaceTextInString(string $text, string $search, string $replace): array {
$count = 0;
if ($search === '') {
return array(
'changed' => false,
'count' => 0,
'text' => $text
);
}
$new_text = str_replace($search, $replace, $text, $count);
$changed = false;
if ($count > 0) {
$changed = true;
}
return array(
'changed' => $changed,
'count' => $count,
'text' => $new_text
);
}
$replace_report = ogSnippetReplaceTextInString('Cylon contact pending', 'pending', 'confirmed');
echo 'Replacement result: '.$replace_report['text'];