Zend PHP 7 Certification – Strings – Replacing

This post covers the Replacing section of the Strings chapter when studying for the Zend PHP 7 Certification.

Some of the string functions for replacing characters in a given string can be seen below.

The str_replace function replaces all occurrences of the search string with the replacement string. It can take up to four parameters.

  • search – The value being searched for, otherwise known as the needle. An array may be used to designate multiple needles.
  • replace – The replacement value that replaces found search values. An array may be used to designate multiple replacements.
  • subject – The string or array being searched and replaced on, otherwise known as the haystack. If subject is an array, then the search and replace is performed with every entry of subject, and the return value is an array as well.
  • count – If passed, this will be set to the number of replacements performed.
$bodytag = str_replace("%body%", "black", "<body text='%body%'>");
// Outputs: <body text='black'>

$str = str_replace("ll", "", "good golly miss molly!", $count);
echo $count; // Outputs: 2

There is also a str_ireplace function, which is a case-insensitive version of str_replace.

The substr_replace replaces a text within a portion of a string. It can take up to four parameters.

  • string – The input string, or an array of strings can be provided (in which case the replacements will occur on each string in turn).
  • replacement – The replacement string.
  • start – If start is non-negative, the replacing will begin at the start’th offset into string. If start is negative, the replacing will begin at the start’th character from the end of string.
  • length – If given and is positive, it represents the length of the portion of string which is to be replaced. If it is negative, it represents the number of characters from the end of string at which to stop replacing.
$var = 'foo bar baz';

/* These two examples replace all of $var with 'hello'. */
echo substr_replace($var, 'hello', 0);
echo substr_replace($var, 'hello', 0, strlen($var));

/* Insert 'hello' right at the beginning of $var. */
echo substr_replace($var, 'hello', 0, 0);

View the other sections:

Note: This article is based on PHP version 7.1.