php preg_replace regex replace string between two string

后端 未结 4 913
余生分开走
余生分开走 2020-12-22 04:28

I have the following problem: I want to replace (in php) a special character, but only if it\'s between two other characters. It tried to find a solution with with preg_repl

相关标签:
4条回答
  • 2020-12-22 04:45

    What about string replace?

    str_ireplace(';";', ':";', $orig_string);
    

    asbas;"asd:";asd;asdadasd;"asd;adsas"

    0 讨论(0)
  • 2020-12-22 04:57

    You need not use look arounds here. It can be written as

    ("[^";]*);([^"]*")
    

    replace with \1:\2

    Regex Demo

    Test

    preg_replace ("/(\"[^\";]*);([^\"]*\")/m", "\\1:\\2", 'asbas;"asd;";asd;asdadasd;"asd;adsas"' );
    => asbas;"asd:";asd;asdadasd;"asd:adsas"
    

    Update:

    ;(?!(?:"[^"]*"|[^"])*$)
    

    Just replace the matched ; with :

    DEMO

    0 讨论(0)
  • 2020-12-22 05:01

    A simple understandable solution could be the use of preg_replace_callback:

    $str = preg_replace_callback('/"[^"]+"/',
           function ($m) { return str_replace(";", ":", $m[0]); },
           $str);
    

    "[^"]+" captures the quoted stuff to $m[0] where ; is replaced by :

    See test at eval.in (link will expire soon)

    0 讨论(0)
  • 2020-12-22 05:05
    ;(?=[^"]*"(?:[^"]*"[^"]*")*[^"]*$)
    

    Try this.Replace by :.See demo.

    https://www.regex101.com/r/bC8aZ4/16

    0 讨论(0)
提交回复
热议问题