Extended behaviour of explode() and str_replace() in PHP

PHP provides various built-in functions to make our server development experience easier. This article is to check some unfamiliar behaviours of explode() and str_replace() functions.

Explode NULL string.

The explode function is used to split a string and forms an array of those substrings. Note that if the string that is fed to the explode() function is an empty or NULL, the array returned from the explode is not empty and consist a 0 key of an empty value. For eg-

$test = NULL;
$val = explode(', ', $test);
if (!empty($val)) {
  echo "Empty array not returned.";

$val will be array(0 => NULL);

This could result in incorrect behaviour in the application and could be avoided using a simple array_filter() function around explode(). This will remove any empty values from the array.

$val = array_filter(explode(', ', $test));

$val is array();


Check if any of the array value is present in a string.

If we have a string value and need to check if any of the value from another array is present in a string, built-in str_replace() can be used to check the same using the fourth parameter provided by the function. For eg.

$test = array('str1', 'str2', 'str3');
$string = 'Search for the value str2';
$count = 0;
str_replace($test, '', $string, $count);
// if replace is successful - the array value is present(Match Found).
if ($count > 0) {
   echo "One of Array value is present in the string.";

There are different ways to attain this, eg using foreach(), explode() etc, but this certainly does better without any looping required in the code.

The above code checks for each value present in $strArr and tries to replace it in the string. If the match is found the $count variable is incremented.