Home > front end >  How to match all characters that are not a-zA-Z and "b4g" (matching numbers except when b4
How to match all characters that are not a-zA-Z and "b4g" (matching numbers except when b4

Time:04-21

Trying to understand the negative lookaheads or positive. Basically I want to match everything that isn't in the capture group [a-zA-Z] and the literal string "b4g". So I would be left with just a-z and the b4g literal if it was in the string.

Given: $100b4gb$2000

It would match $100$200

I would do a regex replace all matches, so they would be replaced with ''. Something like

preg_replace('/(?!.*b4g)[^a-zA-Z] /', '', $subject);

I've tried this and can't get it to work

Matches everything but strips 4 from "b4g"

[^a-zA-Z] 

Can't get this lookahead to work either

(?!.*b4g)[^a-zA-Z] 

CodePudding user response:

You can use

preg_replace('~b4g(*SKIP)(*F)|[^a-zA-Z]~', '', $text)

See the regex demo. Details:

  • b4g(*SKIP)(*F) - matches a b4g substring and omits it from the match, and the next search starts from the failure position
  • | - or
  • [^a-zA-Z] - any char other than an ASCII letter.
  • Related