PHP replace string value from the specific position to the immediate first special character from the string

Solution:1

you can use like this

$new_value = "My New String";
$array     = explode("|",$haystack);
$new_array = array();
foreach($array as $key)
    $new_array[] = (strstr($key,'2547:'))?"2547: ".$new_value:$key;

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

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

Solution:2

You could use str_replace if you know the full value you want to replace:

$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);

You can also use a loop 😱:

$collection = [];

$find = "2547: Second Result";
$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);

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

    $collection[] = $part;
}

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

print_r($result);

These are not the only ways to do this…