【问题标题】:PHP replace string value from the specific position to the immediate first special character from the stringPHP将字符串值从特定位置替换为字符串中的第一个特殊字符
【发布时间】:2021-02-23 14:15:56
【问题描述】:

如何替换指定字符串中匹配部分的字符串值。

例如,

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

现在我想从 2547: 开始更改为第一个 | (管道) 在起始值之后。

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

如何替换 $haystack 变量中的特定字符串的值。

想用第一个匹配字符串替换值到 PHP 中的第一个管道字符。

在给定的字符串中,2547: Second Result|替换为 2547: My New Value| 并保留字符串的其余部分。

是否可以在 PHP 中不使用正则表达式而只使用 strpos() 等常用函数或任何其他 php 字符串函数,或者我们可以使用 preg_replace().

【问题讨论】:

  • 您要替换的值是否已知?如,您只知道数字2547 还是知道整个2547: Second Result 值?
  • @El_Vanja 我知道唯一的开头是数字而不是值。

标签: php


【解决方案1】:

你可以这样使用

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

【讨论】:

    【解决方案2】:

    如果您知道要替换的全部值,则可以使用 str_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);
    

    你也可以使用循环?:

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

    这些不是唯一的方法......

    【讨论】:

    • 我知道唯一以开头但不知道确切字符串值的数字。
    • 好的,我使用循环的第二个解决方案示例将在您没有完整字符串而只有数字的情况下工作
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-07
    相关资源
    最近更新 更多