Regex in php: capture of a symbol that is not at the beginning of the line



  • Need to be replaced abif a is not the first symbol in the line. I'd like that:

    a(?!^)
    

    But it doesn't work like that. ^ doesn't work in brackets.

    All right, let's just say otherwise: abaif a - not the first symbol.



  • You're not using the wrong negative. http://php.net/manual/ru/regexp.reference.assertions.php (negative-lookbehind). We need to do something like this:

    echo(preg_replace("/(?<!^)a/", '', 'abba')); // abb
    

    By the way, the symbol. ^ It works very well in the brackets. You just need to know how to use it;

    https://regex101.com/r/nU9fL9/2

    UPD:

    Alternative, without using the anchor, starting the line:

    echo(preg_replace("/(.)a+/", '$1', 'abaaaaba')); // abb
    



Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2