HTML CSS Bootstrap JavaScript jQuery MySQL PHP Data Mining

PHP String Search & Replace

Manipulating text often involves searching for specific patterns or characters and replacing them with new values. PHP offers a variety of functions that handle both case-sensitive and case-insensitive transformations.


1. Advanced Searching

We've seen strpos(), but there are others that offer more control.

  • strpos(): Find position of the first occurrence.
  • strrpos(): Find position of the last occurrence.
  • stripos(): Case-insensitive search.
<?php
    $text = "The quick brown fox jumps over the lazy dog";
    echo strrpos($text, "the"); // Output: 31 (start of the second 'the')
?>

2. Extracting Substrings

The substr() function extracts a specified part of a string.

<?php
    $str = "Hello World";
    echo substr($str, 6); // Output: World (starts at index 6)
    echo substr($str, 0, 5); // Output: Hello (start at index 0, length 5)
?>

3. Replacing Text

Beyond basic replacement, you can also use str_ireplace() for case-insensitive swaps.

<?php
    $msg = "I love Javascript";
    echo str_ireplace("JAVASCRIPT", "PHP", $msg); 
    // Output: I love PHP (case-insensitive)
?>
Smart Replacement: str_replace() can take an **array** of search and replace values, allowing you to perform multiple swaps in a single line.
<?php
    $find = ["dog", "fox"];
    $replace = ["cat", "wolf"];
    $sentence = "A fox jumps over a dog";
    echo str_replace($find, $replace, $sentence); 
    // Output: A wolf jumps over a cat
?>

Comparison Table

Case-Sensitive Case-Insensitive Action
strpos()stripos()Find First Pos.
strrpos()strripos()Find Last Pos.
str_replace()str_ireplace()Replace Text
Negative Indices: In PHP 7.1+, substr() and strpos() support negative starting positions, allowing you to search relative to the **end** of the string.

Key Takeaways

  • Use substr() to "cut" part of a string.
  • Suffix functions with 'i' for case-insensitive behavior (e.g., stripos).
  • Use arrays with str_replace() for multiple batch updates.
  • Remember that indices for searching and cutting always start at 0.