Find and Replace Substrings in PHP: A Practical Guide

Updated: January 10, 2024 By: Guest Contributor Post a comment

Overview

In this tutorial, we’ll explore how to use PHP’s string manipulation functions, like str_replace() and preg_replace(), to find and replace text within strings. Understanding these functions is crucial for data cleaning, template processing, or setting up dynamic content on the web.

Using str_replace()

The simplest way to replace text in a string is using the str_replace() function, which searches for a given value and replaces it with a new value in a string. Here’s the basic syntax:

// basic syntax
$output = str_replace(search, replace, subject, count);

Here’s an example:

$text = 'The quick brown fox jumps over the lazy dog';
$search = 'fox';
$replace = 'cat';

$newText = str_replace($search, $replace, $text);

echo $newText;

Output:

The quick brown cat jumps over the lazy dog

You can also pass arrays to str_replace() to perform multiple search-replace operations in one go.

$text = 'The quick brown fox jumps over the fox';
$search = array('fox', 'brown');
$replace = array('cat', 'black');

$newText = str_replace($search, $replace, $text);

echo $newText;

Output:

The quick black cat jumps over the cat

Case-Insensitive Replacement

For case-insensitive replacement, you can use str_ireplace(). It works the same way as str_replace() but without considering the case of the strings.

$text = 'The quick brown FOX jumps over the lazy dog.';
$search = 'fox';
$replace = 'cat';

$newText = str_ireplace($search, $replace, $text);

echo $newText;

Output:

The quick brown cat jumps over the lazy dog.

Using substr_replace()

When you need to replace text within a portion of a string, substr_replace() comes in handy. It replaces text starting at a specified position. Let’s replace ‘brown’ with ‘red’ starting at position 10:

$text = 'The quick brown fox jumps over the lazy dog';
$start = 10;
$length = 5;  // 'brown' is 5 characters long
$replace = 'red';

$newText = substr_replace($text, $replace, $start, $length);

echo $newText;

Output:

The quick red fox jumps over the lazy dog

Advanced Replacement with preg_replace()

For more complex replacements involving patterns (like regular expressions), use preg_replace(). Below is an example of replacing all vowels with asterisks:

$text = 'The quick brown fox jumps over the lazy dog';
$pattern = '/[aeiou]/i';
$replace = '*';

$newText = preg_replace($pattern, $replace, $text);

echo $newText;

Output:

Th* q**ck br*wn f*x j*mps *v*r th* l*zy d*g

You can also use captured groups and backreferences within preg_replace() to perform more advanced operations.

Handling Replacement with Callbacks

What if you want more control over how replacements are made? PHP’s preg_replace_callback() can be used. This function allows us to replace part of a string based on matches found with a regular expression, the callback function then determines what the replacement should be. Here’s how you can use it to capitalize every word in a string:

$text = 'The quick brown fox jumps over the lazy dog';
$pattern = '/\b[a-z]/i';

$newText = preg_replace_callback(
    $pattern,
    function ($matches) {
        return strtoupper($matches[0]);
    },
    $text
);

echo $newText;

Output:

The Quick Brown Fox Jumps Over The Lazy Dog

This method provides a powerful way to handle complex string manipulations with custom logic.

Regex Patterns and Modifiers

Understanding regular expression patterns and modifiers expands the power of preg_replace() and preg_replace_callback(). Patterns allow you to specify the string to match in complex ways, and modifiers alter the way the pattern is matched (e.g., case-insensitive matching with ‘i’). Mastering these can supercharge your find and replace capabilities.

See also:

Conclusion

Manipulating strings with PHP is straightforward once you’re familiar with its string functions. From simple replacements with str_replace() to complex pattern matching with preg_replace(), PHP provides robust tools for nearly any use case. I hope this guide has empowered you to confidently use these functions in your future projects.