Search and Replace in Joomla
There are cases where you would like to do some replacements in your site output. This is a common search and replace in Joomla need for site administrators when they want quick global fixes, branding updates, or cleanup changes. Hopefully, you don't need an extra plugin. You can do it with Tassos Code Snippets using a simple PHP snippet.
The PHP Snippet Code
This code lets you define all your search-and-replace rules in one place and apply them to the final HTML output of your site. It supports both simple text replacements and regex-based replacements, so you can handle straightforward text updates and pattern-based transformations.
use Joomla\CMS\Factory;
// Edit your search-and-replace rules here.
$replacements = [
[
'search' => '#Old Company Name#',
'replace' => 'New Company Name',
],
[
'search' => '#old-domain\.com#',
'replace' => 'new-domain.com',
],
];
// Do not edit below.
$app = Factory::getApplication();
$app->registerEvent('onAfterRender', function () use ($app, $replacements)
{
$document = $app->getDocument();
// Skip non-HTML responses.
if (!$document || $document->getType() !== 'html')
{
return;
}
$body = $app->getBody();
if (!is_string($body) || $body === '')
{
return;
}
$newBody = $body;
// Apply each replacement rule.
foreach ($replacements as $rule)
{
if (empty($rule['search']))
{
continue;
}
$newBody = preg_replace($rule['search'], $rule['replace'] ?? '', $newBody);
}
// Update output only when something changed.
if ($newBody !== $body)
{
$app->setBody($newBody);
}
});
How to add this snippet
- Install Tassos Code Snippets if it is not installed already.
- Go to your Joomla Administrator area.
- Open Components → Tassos Code Snippets.
- Click New.
- Select PHP as the snippet type.
- Paste the code above.
- Select Insertion Method → Page Load.
- Publish the snippet.
- Optionally, open the Conditional Logic tab to restrict which pages or users the snippet runs on. Leave it empty to run it site-wide. Learn more in Using Snippet Logic.
Congratulations! You've just added search-and-replace functionality to Joomla without installing another plugin or adding unnecessary bloat to your site. For more details, visit the PHP Snippet documentation.
Use Cases
- Fix typos globally
- Update branding/terminology
- Replace URLs
- Modify content automatically
- Clean up output
- Replace old company name
- Update deprecated terms
- Fix common misspellings
- Replace HTTP with HTTPS links
- Remove unwanted text