代码之家  ›  专栏  ›  技术社区  ›  Mark L

仅使用php的mb_ereg_replace替换第一个匹配元素

  •  0
  • Mark L  · 技术社区  · 16 年前

    我只想替换字符串中的第一个匹配元素,而不是替换字符串中的每个匹配元素

    $str = 'abc abc abc';
    $find = 'abc';
    $replace = 'def';
    echo mb_ereg_replace( $find, $replace, $str );
    

    这将返回“def def def”。

    为了让$find或$replace参数返回“def abc abc”,我需要更改什么?

    3 回复  |  直到 14 年前
        1
  •  1
  •   Jens    16 年前

    不是很优雅,但你可以试试

    $find = 'abc(.*)'; 
    $replace = 'def\\1'; 
    

    请注意,如果 $find 包含更多捕获组,您需要调整 $replace . 此外,这将取代每行的第一个ABC。如果输入包含多行,请使用 [\d\D] 而不是 . .

        2
  •  1
  •   ghostdog74    16 年前

    你可以做 mb_strpos() 对于“ABC”,那么 mb_substr()

    $str = 'blah abc abc blah abc';
    $find = 'abc';
    $replace = 'def';
    $m  = mb_strpos($str,$find);
    $newstring = mb_substr($str,$m,3) . "$replace" . mb_substr($str,$m+3);
    
        3
  •  0
  •   Mat Kay Adam Hopkinson    14 年前

    除非你需要昂贵的regex替代品,否则最好用普通的 str_replace ,这需要 $count 作为第四个参数:

    $str = str_replace($find, $replace, $str, $count);
    
    推荐文章