Search⌘ K
AI Features

Replacing Strings within a Portion of an Existing String

Explore how to use Laravel's substrReplace helper method to replace or insert text within specific portions of strings. Understand offset and length parameters, apply replacements selectively using array manipulations, and handle practical scenarios such as modifying BASIC program lines without affecting line numbers.

The substrReplace helper method

This is an interesting one. At a high level, we can use it to replace portions of an existing string.

PHP
<?php
/**
* Versions: Laravel 8, 9
*
* @return string|array
*/
public static function substrReplace(
string|array $string,
string|array $replace,
array|int $offset = 0,
array|int|null $length = null
);

That can be a confusing explanation, so we can think of it as being capable of doing the following (and more):

  • Inserting text into a current string at a specific location
  • Replacing text in an existing string at a specific location
  • Skipping parts of a string while performing string replacements

In the following example, we will use the substrReplace helper method to replace the last character of our string by supplying the value -1 as our argument for the offset parameter. When our offset is ...