代码之家  ›  专栏  ›  技术社区  ›  valepu

只知道位置和结构时替换子串

  •  1
  • valepu  · 技术社区  · 7 年前

    我有这样的情况,我有一个字符串,我必须更换某些部分。我知道这些部分在哪里,它们看起来像什么(换句话说,我可以通过regex匹配它们),但我不仅不知道确切的内容,而且在字符串中可能有类似的子字符串。 我想要实现的是只替换该偏移处的特定引用,而保留其余部分不变。

    举个例子:

    Test String (this) Test (not this) Test Test (this) Test Test (and this) Test (this maybe)
    

    我知道必须替换与此正则表达式匹配的字符串: \(.*?\) 但前提是他们先摆姿势 12, 62 and 78 (换句话说,第一个 (this) (and this) (this maybe) . 子串 (not this) 第二个呢 不得更换)

    我知道我应该发布我的问题尝试,但我盯着代码,因为半个小时,没有想法出来了(我已经盯着代码很长时间,然后放弃并要求在过去,但今天我有点匆忙),但我有这种感觉,解决办法比我想的简单。我唯一意识到的是,我应该以相反的顺序替换字符串,这样我就不会修改位置

    1 回复  |  直到 7 年前
        1
  •  2
  •   rickdenhaan    7 年前

    我想到的是:

    $string = 'Test String (this) Test (not this) Test Test (this) Test Test (and this) Test (this maybe)';
    
    $offsets = [12, 62, 78];
    $replace = "REPLACED";
    
    // work backwards so we don't have to keep track of changing offsets
    rsort($offsets);
    
    foreach ($offsets as $offset) {
        $string = preg_replace('/^(.{' . $offset . '})\([^\)]*\)/', '$1'.$replace, $string);
    }
    
    echo $string;
    // Test String REPLACED Test (not this) Test Test (this) Test Test REPLACED Test REPLACED
    

    (this) 未被替换,因为它不是从偏移量12、62或78开始的。如果将它添加到 $offsets 它也将被替换。

    我在测试中注意到 \(.*\) \([^\)*\) \(.*\) 同样匹配 (this) Test (not this)

    推荐文章