简体   繁体   中英

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

How to replace string value from the matching part in the specified string.

Exmaple,

$haystack = "2548: First Result|2547: Second Result|2550: Third Result|2551: Fourth Result

Now I want to change starting from 2547: to the first | (pipe) after the starting value.

$result = "2548: First Result|2547: My New String|2550: Third Result|2551: Fourth Result

How can I replace the value of the Specific string from the $haystack variable.

Want to replace value with first matching string to immediate first pipe character in PHP.

In the given string, 2547: Second Result | replace with 2547: My New Value| and remaining part of the string as it is.

Is it possible without using Regular express in PHP and just use common function like strpos() or any other php string function or we can do it easily using preg_replace() .

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
*/

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...

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM