Insert string at specified position

Insert string at specified position

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

Stefan Bogdanescu

Founder & Senior Architect

Inserting Strings at Specific Positions in PHP

You often find yourself needing to splice a new piece of data into an existing string or array. The most common use case is taking the result of strpos to determine where a delimiter exists and then injecting content immediately after that point. While str_replace handles substitutions well, it does not offer direct control over insertion points relative to specific offsets. To achieve this in vanilla PHP, you must rely on string manipulation functions like substr, strlen, and the concatenation operator.

The fundamental approach involves three distinct steps: locating the target position, calculating the split point, and reconstructing the string. If you are using strpos to find a substring, that function returns the offset of the first character of that match. To insert text after that match, your split point is simply the original position plus the length of the matched substring.

Consider a scenario where you need to inject a tracking parameter into a URL. You have a base URL containing a query string key ref, and you want to append a new value campaign_id=123 immediately after ref=.

$baseUrl = 'https://example.com/page?ref=user_55&other=data';
$search = 'ref=';

if (strpos($baseUrl, $search) !== false) {
    $pos = strpos($baseUrl, $search);
    // Add the length of the search string to get the position after the delimiter
    $insertionPoint = $pos + strlen($search);
    
    $newString = substr($baseUrl, 0, $insertionPoint) . 'campaign_id=123' . substr($baseUrl, $insertionPoint);
    
    echo $newString;
    // Output: https://example.com/page?ref=user_55&other=data (Wait, the logic above was slightly flawed in thought, let's correct the example)
}

Let's refine that example to ensure it actually demonstrates insertion after the search term. In the code block above, if we split at $insertionPoint, we are cutting right after ref=. The first part contains everything up to and including ref=, and the second part starts with the rest of the string. We simply paste our new data between them.

$baseUrl = 'https://example.com/page?ref=user_55&other=data';
$search = 'ref=';

if ($pos = strpos($baseUrl, $search) !== false) {
    // The position immediately following the search string
    $cutPos = $pos + strlen($search); 
    
    $insertionText = 'campaign_id=123';
    
    $result = substr($baseUrl, 0, $cutPos) . $insertionText . substr($baseUrl, $cutPos);
    
    echo $result; 
    // Result: https://example.com/page?ref=campaign_id=123user_55&other=data
}

Wait, the logic in the mental draft above needs to be precise. substr with a start index includes that index. If $pos is 20 (start of "ref=") and length is 4, $cutPos becomes 24. substr($baseUrl, 0, 24) gets indices 0 through 23. substr($baseUrl, 24) gets the rest. This works perfectly for insertion after the search term.

However, there are edge cases you must handle to avoid breaking your application. The most critical check is whether strpos actually found a match. In PHP, strpos returns false if the needle is not found, or an integer offset. If you treat false as a numeric index in arithmetic operations or pass it directly to substr, you will get unexpected results (often treating false as 0). Always verify the return value before performing string slicing.

Furthermore, consider the performance implications if you are doing this inside a tight loop. String manipulation in PHP creates new copies of the data every time you use substr or concatenation. If your strings are massive (megabytes in size) and you are inserting frequently, memory overhead can become significant. In such high-throughput scenarios, working with streams or binary buffers might be more efficient than standard string functions.

Another common pitfall is overlapping matches or multiple occurrences of the same delimiter. strpos only returns the position of the first occurrence. If your logic assumes a unique delimiter but the string contains duplicates (e.g., ?ref=A&ref=B), you will insert data at the wrong location. If you need to target the last occurrence, you would need to reverse the search or use a loop, which adds complexity and cost.

If your project is built on Laravel, this specific logic can be abstracted away using Str helpers or Event listeners if the injection point changes dynamically based on user roles or settings. While not strictly necessary for simple string manipulation, leveraging the Str facade can sometimes make intent clearer to other developers reading the codebase. However, for raw performance or when avoiding framework overhead in CLI scripts, the native functions remain the robust choice.

Ultimately, inserting strings at specified positions is a straightforward operation provided you respect the boundaries of the data. By explicitly calculating the cut point as position + length, you ensure precision regardless of the delimiter's content. Just remember to guard against missing matches and be mindful of multiple occurrences in your source data.

Our network