Replace or insert characters into a string based on a numeric position in the string

Replace or insert characters into a string based on a numeric position in the string

  1. Blog
  2. 15 November 2026
  3. 4 min read

Stefan Bogdanescu

Founder & Senior Architect

Replacing and Inserting Characters in PHP Strings

PHP offers a robust set of built-in functions for manipulating strings, but finding a direct function to replace or insert a character at a specific numeric position requires looking beyond simple substring operations. While str_replace is excellent for replacing substrings based on patterns, it does not natively accept an integer index to target a specific byte or character within the string. Similarly, there is no built-in insert_at() function like one might find in array manipulation libraries. To achieve this, developers typically rely on substring concatenation using substr or utilize the powerful strtr and mb_strcut functions depending on the encoding requirements of the application.

Replacing a Character at a Specific Index

The most straightforward approach to replace a character at position $i with a new character $x involves slicing the string into two parts: the segment before the target index and the segment after it. This technique leverages the fact that substr allows you to specify a length of zero for the second part, effectively truncating the string at the desired point without including the original character.

Consider a function that accepts a string, an integer position (0-indexed), and a replacement character:

function replaceAt(string $string, int $i, string $char): string {
    if ($i < 0 || $i >= mb_strlen($string)) {
        throw new InvalidArgumentException('Index out of bounds');
    }

    $length = mb_strlen($string);
    
    // If the replacement character is longer than one unit (e.g., multi-byte),
    // we need to adjust the slice logic or ensure $char fits.
    // For single-byte replacements, this simple approach works:
    
    $before = substr($string, 0, $i);
    $after = substr($string, $i + 1);
    
    return $before . $char . $after;
}

This implementation uses mb_strlen to ensure the index is validated against the actual number of characters, not bytes. This is crucial when dealing with UTF-8 encoded strings containing emojis or accented characters. If you simply check against strlen, you might accidentally target the middle of a multi-byte character sequence, resulting in corrupted output.

Inserting Substrings at a Position

The logic for insertion is nearly identical but requires handling two distinct scenarios: inserting before the specified index and inserting after it. When using substr for insertion, you split the original string into the prefix (everything up to $i) and the suffix (everything starting from $i). Concatenating the new substring in between yields the desired result.

function insertAt(string $string, int $i, string $insert): string {
    // Ensure we don't go out of bounds for insertion point
    if ($i < 0 || $i > mb_strlen($string)) {
        throw new InvalidArgumentException('Insertion position invalid');
    }

    $before = substr($string, 0, $i);
    $after = substr($string, $i);
    
    return $before . $insert . $after;
}

Notice the adjustment in the validation logic. When inserting, a position equal to the length of the string is valid (appending to the end), whereas when replacing, the index must strictly be less than the length because there must be an existing character to overwrite. This subtle distinction prevents runtime errors and logic bugs in production code.

Handling Multi-Byte Encodings and Edge Cases

A common pitfall in PHP string manipulation is ignoring multi-byte character sets. Using substr on a UTF-8 string using byte indices rather than character indices can lead to data corruption. For instance, replacing the middle of a 4-byte emoji without accounting for its full width will split the UTF-8 sequence, breaking the character encoding and causing invalid characters or mojibake in the output.

Always prefer mb_strlen, mb_substr, or the mb_strcut helper introduced in PHP 8.2 over their byte-based counterparts when working with international content. If you are using the native substr functions, ensure you pass the $encoding parameter if available, though it is often omitted for ASCII-only strings where performance is critical and simplicity is preferred.

For complex scenarios involving regular expressions or pattern replacement, consider leveraging preg_replace_callback. This allows you to match a specific character at an index without hardcoding the string slicing logic, providing a more declarative approach:

function replaceRegexAt(string $string, int $i, string $replacement): string {
    // Create a regex that matches exactly i characters from the start
    $pattern = '/^{' . $i . '}(.)/'; 
    // Note: This is a simplified conceptual example. 
    // In practice, direct slicing is usually more performant for single replacements.
    
    return preg_replace_callback($pattern, function ($matches) use ($replacement) {
        return $replacement;
    }, $string, 1);
}

While regex offers flexibility, direct string manipulation via substr remains the most efficient and readable solution for simple index-based modifications. If you require advanced text processing capabilities beyond basic replacement or insertion, exploring dedicated packages or leveraging Laravel's built-in helpers can simplify the implementation further. For more complex string utility needs in a Laravel application, check out resources like https://laravelcompany.com to see how community-driven packages extend core functionality.

Our network