Searching and replacing text

PHP:
Searching and replacing text

How to:

Here’s a quick way to replace ‘cat’ with ‘dog’ in a sentence using PHP:

<?php
$text = 'The quick brown fox jumps over the lazy cat';
$replacedText = str_replace('cat', 'dog', $text);

echo $replacedText;
?>

Sample Output:

The quick brown fox jumps over the lazy dog

Now, suppose we’re dealing with case-insensitive replacement:

<?php
$text = 'Catapults are CATegorically amazing!';
$replacedText = str_ireplace('cat', 'dog', $text);

echo $replacedText;
?>

Sample Output:

Dogapults are DOGegorically amazing!

Deep Dive:

Search and replace functions have been around since the early days of computing — think sed in Unix. In PHP, str_replace and str_ireplace are your go-to for a simple search and replace. str_replace is case-sensitive, while str_ireplace isn’t.

How do they work? Under the hood, both functions check each part of the string, look for matches, and replace them. They handle arrays too, so you can search and replace multiple patterns in one go.

Now, if you need more control, like pattern matching, you’ll want to use preg_replace. This utilizes regular expressions, offering much more flexibility and precision:

<?php
$text = 'The quick brown fox jumps over the lazy cat 7 times.';
$replacedText = preg_replace('/\bcat\b/i', 'dog', $text);

echo $replacedText;
?>

Sample Output:

The quick brown fox jumps over the lazy dog 7 times.

This replaced ‘cat’ with ‘dog’, ignoring case (/i modifier), and matched whole words only (\b word boundary).

See Also: