This situation is the first time that I've seen lookarounds outperform \K
. Interesting.
Typically capture groups and lookarounds cost additional steps. But due to the nature of this task, the regex engine can navigate the string faster in search of the aaa
then look back for a start of the string anchor.
I'll add a couple of \K
patterns for comparison.
I am using the s
pattern modifier in case the leading character might be a newline character (which .
would not normally match). I just thought I would add this consideration to preemptively address a fringe case that I may be posed.
Again, this is an enlightening scenario because in all other regex cases that I've dealt with \K
beats out the other techniques.
Step Count Comparison Matrix:
| `~.\Kaaa~s` | `~.+?\Kaaa~s` | `(?<!^)aaa` | `(?!^)aaa` | `.(aaa)` |
--------------|-------------|---------------|-------------|------------|----------|
`aaa bbb ccc` | 12 steps | 67 steps | 8 steps | 8 steps | 16 steps |
--------------|-------------|---------------|-------------|------------|----------|
`bbb aaa ccc` | 15 steps | 12 steps | 6 steps | 6 steps | 12 steps |
The take away is: To learn about the efficiency of your patterns, spit them into regex101.com and compare the step counts.
Also, if you know exactly what substring you are looking for and you don't need a regex pattern, then you should be using strpos()
as a matter of best practice (and just check that the returned value is > 0
)
...in other words:
if (strpos($haystack, 'aaa')) {
// 'aaa' is "truthy"
// 'aaa' is found and not positioned at offset zero
}
aaa
? Replacing it with what? – Doorpost