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.
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')
?>
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)
?>
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)
?>
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
?>
| Case-Sensitive | Case-Insensitive | Action |
|---|---|---|
strpos() | stripos() | Find First Pos. |
strrpos() | strripos() | Find Last Pos. |
str_replace() | str_ireplace() | Replace Text |
substr() and strpos() support negative starting positions, allowing you to search relative to the **end** of the string.
substr() to "cut" part of a string.stripos).str_replace() for multiple batch updates.