How can I replace part of a string in PHP starting from a specific position up to the first special character?

Solution: 1

You can replace a specific part of a delimited string using explode(), strstr(), and implode():


$new_value = "My New String";
$haystack  = "2548: First Result|2547: Old Value|2550: Third Result|2551: Fourth Result";

$array     = explode("|", $haystack);
$new_array = [];

foreach ($array as $item) {
    $new_array[] = (strstr($item, '2547:')) ? "2547: " . $new_value : $item;
}

$result = implode("|", $new_array);
print_r($result);

/*
Output:
2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result
*/

✅ This approach scans each segment, replaces the one starting with 2547:, and then reconstructs the string.

Solution: 2

If you know the full value you want to replace, str_replace() is the simplest approach:


$find = "2547: Second Result";
$replace = "2547: My New Value";
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result";

$result = str_replace($find, $replace, $haystack);
print_r($result);

/*
Output:
2548: First Result|2547: My New Value|2550: Third Result|2551: Fourth Result
*/

Using a loop for partial or dynamic matching

If you only know part of the value (e.g., the ID), you can loop through the segments:


$collection = [];
$find = "2547"; // only the ID
$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result";

$parts = explode('|', $haystack);

foreach ($parts as $part) {
    [$id, $old_value] = explode(':', $part, 2);

    if ($id === $find) {
        $part = "{$id}: My New Value";
    }

    $collection[] = $part;
}

$result = implode('|', $collection);
print_r($result);

/*
Output:
2548: First Result|2547: My New Value|2550: Third Result|2551: Fourth Result
*/