Tags
PHP
Asked 3 years ago
9 Jun 2021
Views 260
pratik

pratik posted

strrchr with strtr or str_replace in PHP

strrchr with strtr or str_replace in PHP
jabber

jabber
answered Apr 25 '23 00:00

strrchr, strtr, and str_replace are all PHP string functions with different purposes.

strrchr finds the last occurrence of a character or substring in a string and returns everything after it. For example:



$string = "hello world";
$substring = strrchr($string, "o");
echo $substring; // outputs "orld"

strtr translates characters or replaces substrings in a string based on a given translation table. For example:



$string = "hello world";
$translation = array("o" => "0", "l" => "1");
$new_string = strtr($string, $translation);
echo $new_string; // outputs "he110 w0rld"

str_replace replaces all occurrences of a substring in a string with another substring. For example:



$string = "hello world";
$new_string = str_replace("o", "0", $string);
echo $new_string; // outputs "hell0 w0rld"

To replace a whole word in a string , you can use str_replace or a regular expression with preg_replace. For example:



$string = "The quick brown fox jumps over the lazy dog";
$new_string = str_replace("fox", "cat", $string);
echo $new_string; // outputs "The quick brown cat jumps over the lazy dog"

// or

$new_string = preg_replace("/\bfox\b/", "cat", $string);
echo $new_string; // outputs "The quick brown cat jumps over the lazy dog
"
The \b in the regular expression matches a word boundary, so it only matches the word "fox" and not substrings like "foxy".
Post Answer