Finding and Replacing Text in PHP Strings: str_replace() vs. preg_replace()

Finding and Replacing Text in PHP Strings: str_replace() vs. preg_replace()

Learn how to find and replace text in PHP using str_replace() and preg_replace(). Understand their differences and use cases for efficient text processing.

Introduction

Replacing text within strings is a common task in PHP development. Whether you need to modify user input, clean up content, or format text dynamically, PHP provides multiple ways to find and replace text efficiently.

Two primary functions for text replacement in PHP are:

  • str_replace() – A simple function for replacing exact matches in a string.
  • preg_replace() – A powerful function that supports regular expressions for advanced pattern matching.

This guide covers:

  • How str_replace() and preg_replace() work
  • When to use each function
  • Performance differences
  • Practical examples for replacing words, patterns, and special characters

1. Replacing Text with str_replace()

The str_replace() function replaces all occurrences of a search string with a given replacement.

Basic Syntax

str_replace(string $search, string $replace, string|array $subject): string|array
  • $search – The text to find.
  • $replace – The text to replace it with.
  • $subject – The input string or array to search in.

Example: Basic Text Replacement

$text = "Hello, world!";
$result = str_replace("world", "PHP", $text);

echo $result; // Output: Hello, PHP!

str_replace() replaces all occurrences, not just the first one.

Example: Replacing Multiple Words

$text = "Roses are red, violets are blue.";

$search = ["red", "blue"];
$replace = ["green", "yellow"];

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

echo $result; // Output: Roses are green, violets are yellow.
  • The function allows multiple words to be replaced in one call.
  • The replacement is case-sensitive.

2. Replacing Text Using preg_replace()

preg_replace() allows for pattern-based replacements using regular expressions (regex).

Basic Syntax

preg_replace(string|array $pattern, string|array $replacement, string|array $subject, int $limit = -1): string|array|null
  • $pattern – A regular expression pattern to match.
  • $replacement – The replacement text.
  • $subject – The input string or array to search in.
  • $limit – The maximum number of replacements (default is unlimited).

Example: Replace Words Using Regular Expressions

$text = "I have 100 apples and 50 oranges.";

$result = preg_replace("/[0-9]+/", "X", $text);

echo $result; // Output: I have X apples and X oranges.
  • The pattern /[0-9]+/ matches any number of digits and replaces them with "X".
  • Unlike str_replace(), preg_replace() supports pattern-based replacements.

Example: Case-Insensitive Word Replacement

$text = "Welcome to PHP! php is fun.";

$result = preg_replace("/php/i", "Laravel", $text);

echo $result; // Output: Welcome to Laravel! Laravel is fun.
  • The i flag makes the regex case-insensitive, replacing "php" regardless of letter case.

3. Key Differences Between str_replace() and preg_replace()

Feature str_replace() preg_replace()
Exact match replacement ✅ Yes ✅ Yes
Pattern-based replacement ❌ No ✅ Yes
Case-insensitive replacement ❌ No ✅ Yes (with i flag)
Replacing multiple words ✅ Yes (array input) ✅ Yes (regex patterns)
Performance 🔹 Faster for simple replacements 🔹 Slower due to regex processing
  • Use str_replace() when replacing known words or characters.
  • Use preg_replace() for complex patterns, case-insensitivity, or special character handling.

4. Replacing Special Characters and Formatting Strings

Removing Non-Alphanumeric Characters

$text = "Hello! How's it going? (Good!)";

$clean_text = preg_replace("/[^a-zA-Z0-9\s]/", "", $text);

echo $clean_text; // Output: Hello Hows it going Good
  • The pattern /[^a-zA-Z0-9\s]/ removes everything except letters, numbers, and spaces.

Replacing Multiple Spaces with a Single Space

$text = "This    is   a    test.";

$clean_text = preg_replace("/\s+/", " ", $text);

echo $clean_text; // Output: This is a test.
  • \s+ matches one or more spaces and replaces them with a single space.

5. Performance Considerations

  • str_replace() is faster for simple replacements because it doesn’t process regex patterns.
  • preg_replace() is slower because it interprets and executes a regular expression engine.
  • If only simple word replacements are needed, use str_replace().

Performance Test

$text = str_repeat("Hello world! ", 100000); // Large text block

$start = microtime(true);
str_replace("world", "PHP", $text);
echo "str_replace() Time: " . (microtime(true) - $start) . " seconds\n";

$start = microtime(true);
preg_replace("/world/", "PHP", $text);
echo "preg_replace() Time: " . (microtime(true) - $start) . " seconds\n";
  • str_replace() will be significantly faster in this test.
  • preg_replace() is only necessary for advanced use cases.

6. Best Practices for Replacing Text in PHP

✅ Use str_replace() for simple word replacements to maximize speed.
✅ Use preg_replace() when dealing with patterns, case-insensitivity, or complex rules.
✅ Optimize regex patterns to avoid performance issues in preg_replace().
✅ Always validate user input before running replacements to prevent security vulnerabilities.
✅ Consider using preg_replace_callback() for dynamic replacements where the replacement value depends on the match.

Conclusion

Both str_replace() and preg_replace() are powerful tools for modifying text in PHP. Choosing the right function depends on whether simple word replacement or advanced pattern matching is needed.

This guide covered:

  • How str_replace() replaces exact words
  • How preg_replace() works with regular expressions
  • Key differences between the two methods
  • Performance comparisons and best practices

By selecting the correct approach, you can efficiently handle text replacements in PHP applications while ensuring speed, accuracy, and maintainability.

Leave a Reply