Comparing And Replacing String In PHP

Just like the title says, we will learn how to compare and replace string in PHP by using the predefined function in PHP.

In comparing the string, you can either do it regardless the case type or CASE-INSENSITIVE and you can also compare string in regards of its case type or CASE-SENSITIVE.

While replacing string is quite simple. E.g: "Hellow World" and you want to replace the word "World" with "Alex". And so, the final string will be "Hello Alex".

//comparing strings
$s1="Hello world";
echo strcmp($s1, $s2)."<br>"; //compares two strings (case-SENSITIVE)
//It returns 0 if both strings are EQUAL. Otherwise, it returns 1
echo strcasecmp($s1, $s2)."<br>"; //compares two strings (case-INSENSITIVE)
echo "</br>";

//replacing string
$st="Hello world";
echo str_replace("world", "Alex", $st)."<br>";

Copy and paste the coding above and see how it works or you can use PHP online compiler HERE. Good Luck!

Labels: , , , , , , , , , , , ,