PHP substr_replace() Tutorial πŸš€

beginner
12 min

PHP substr_replace() Tutorial πŸš€

Welcome to our PHP substr_replace() tutorial! In this comprehensive guide, we'll explore this powerful string function that helps you replace a part of a string with another string. Let's dive in! 🎯

Understanding substr_replace() πŸ“

The substr_replace() function in PHP replaces a specified portion of a string with a new substring. It takes three parameters: the original string, the substring to be replaced, and the starting position of the replacement.

php
substr_replace(string $subject, mixed $replace, int $start [, int $length])
  • $subject: The original string from which a part will be replaced.
  • $replace: The new substring to replace the specified portion.
  • $start: The position from where the replacement will start.
  • $length: The number of characters to be replaced (optional, defaults to the rest of the string after $start).

Replacing a Substring πŸ’‘

Let's see a practical example to understand how substr_replace() works:

php
$text = "Hello World"; $new_text = substr_replace($text, "Hi", 5); echo $new_text; // Output: Hi World

In this example, we're replacing the word "World" with "Hi" starting from the 5th character.

Advanced Example: Replacing Part of a User's Name βœ…

Sometimes, you may need to replace part of a user's name based on their preferences. Here's how you can do it:

php
$name = "John Doe"; $first_name = substr_replace($name, "", 0, strpos($name, " ")); $last_name = substr_replace($name, "", strpos($name, " ") + 1); echo $first_name; // Output: John echo $last_name; // Output: Doe

In this example, we're extracting the first and last names from the string "John Doe".

Replacing a Specific Number of Characters πŸ“

If you want to replace a specific number of characters, you can use the optional $length parameter:

php
$text = "Hello World"; $new_text = substr_replace($text, "Hi", 0, 5); echo $new_text; // Output: Hi World

In this example, we're replacing the first 5 characters of the string with "Hi".

Quiz Time! 🎯

Quick Quiz
Question 1 of 1

Which PHP function replaces a part of a string with another string?

Remember, practice makes perfect! Keep coding and happy learning! πŸ’»βœ¨