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.
<?php
$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.
start
is negative, the replacing will begin at the start’th character from the end of string.
<?php
$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.