PHP substr_replace

substr_replace()-Replace a part of string

The substr_replace() function is complementary to the function that we discussed earlier – “str_replace()”. While in “str_replace()”, we specified the value that had to replaced, in “substr_replace()”, we specify the starting and the end points of the value to be replaced. It is a more mathematical function. “substr_replace” has four parameters. The syntax is as follows:

substr_replace(original, replace, start, length);

Let’s have a look at the above syntax:

  • original : The string in which replacement function has to be performed.
  • replace : The value with which the value has to be replaced.
  • start : The starting point from where the replacement has to start. It has to be a number. In case there is a negative number, it means number of characters from the end of the string.
  • length : It is an optional parameter. This value tells how many characters beginning from the “start” value have to be replaced. In case the value is negative, it means number of characters from the end of the string.

Now let’s see this with an example.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7,3);
$str_boy=substr_replace($str, "boy", -3, 2);
echo "Girl:".$str_girl."<br/>;
echo "Boy:".$str_boy;
?>

The output of the above code will be:

Girl:I am a girl!
Boy:I am a boy!

The fourth parameter, length is optional. What will happen if we dont use this parameter? Let’s see.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7);
$str_boy=substr_replace($str, "boy", -3);
echo "Girl:".$str_girl."<br/>;
echo "Boy:".$str_boy;
?>

The output of the above script will be:

Girl:I am a girl
Boy:I am a boy

This is the desired output. But do you see any difference in this output and the output above. The exclamation mark at the end of the statement is missing. The reason is that when you do not specify the length parameter, it replaces all the characters from the starting point to the end of the string, with the replace string.


Perform INSERT

The substr_replace function can also be used to insert a value in a string without replacing anything, simply by putting the parameter, length to 0. Let’s add something in our string above.

<?php
$str="I am a sex!";
$str_girl=substr_replace($str, "girl", 7, 3);
$str_boy=substr_replace($str, "boy", -3, 2);
echo "Girl:".substr_replace($str_girl, "good ", 7, 0)."<br/>;
echo "Boy:".substr_replace($str_boy, "good " , -3, 0);
?>

The output will be:

Girl:I am a good girl!
Boy:I am a good boy!

This has performed our insert function.

Previous Post

Comments are closed.