'How to match all characters that are not a-zA-Z and "b4g" (matching numbers except when b4g is encountered)?
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]+
Solution 1:[1]
You can use
preg_replace('~b4g(*SKIP)(*F)|[^a-zA-Z]~', '', $text)
See the regex demo. Details:
b4g(*SKIP)(*F)- matches ab4gsubstring 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.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Wiktor Stribiżew |
