PHP Replace Character in String at Index

I’m writing every article I think will help you in some way. in that respect PHP Replace Character in String at Index This article will be very useful for you.

The substr_replace is an in-built function of PHP, which replaces a part of the string with another text within a string. PHP 4+ versions support this function. The index in the original string is passed as a parameter to which the replacement is to be performed. 

PHP Replace Character in String at Index

The syntax will show below for your reference.

substr_replace($string, $replacement, $start, $length)

Parameters

  • str − The string to check
  • replacement − The string to insert
  • begin − The position from where the replacement begins −
    • If begin is a positive number: Begin replacing at the specified position in the string
    • If begin is a n number: – Begin replacing at the specified position from the end of the string
    • if begin is 0 – Begin replacing at the first character in the string.
  • len − The number of characters to be replaced. The default is the same length as the string.
    • If len is a positive number – The length of string to be replaced
    • If len is a negative number – How many characters should be left at end of string after replacing
    • If len is 0 – Insert instead of replace

PHP Replace Character in String at Index

<?php
  
echo substr_replace("Hello World", "Reader", 6);
  
?>

Output

Hello Reader

PHP Replace Character in String at Index

<?php
  
echo substr_replace("Subscribe Codingdiksha", "to ", 10, 0);
  
?>

Output

Subscribe to Codingdiksha

Program 3

<?php
  
echo substr_replace("Menberra", "Ca", 0, 2);
  
?>

Output

Canberra

Program 4

<?php
  
echo substr_replace("adding", "co", 0, -4);
  
?>

Output

Coding

Program 5

<?php
  
echo substr_replace("icecakes", "cream", -5);
  
?>

Output

icecream

Read Also:

Final Words

PHP Replace Character in String at Index Thank you for reading this useful article. Also, let us know if you have any doubts about this article. We are committed to helping you.

Hi, I'm Ranjith a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Deekshi. Here, I post about programming to help developers.

Share on:

Leave a Comment