29. Regexp
This section covers Regular Expressions (Regex) in PHP, focusing on PCRE functions, advanced syntax, and best practices, as inspired by RexEgg.
What is Regex?
JuniorAnswer: Regex (Regular Expression) is a powerful tool for text matching, searching, and manipulation. In PHP, it is implemented through the PCRE library. Detailed Regexp Guide
Why is Regex good?
JuniorAnswer: It is concise, powerful, and extremely efficient when written correctly. It allows complex text patterns to be described in a single line. Detailed Regexp Guide
How to use Regex in PHP?
JuniorAnswer: PHP uses preg_* functions like preg_match(), preg_match_all(), and preg_replace(). Patterns must be enclosed in delimiters (e.g., /pattern/).
Detailed Regexp Guide
What is the difference between preg_match and preg_match_all?
Junior
Answer: preg_match stops after the first match, while preg_match_all finds all occurrences in the string.
Detailed Regexp Guide
How would you build a complex Regex step-by-step?
MiddleAnswer: 1. Identify what to ignore (quotes, tags). 2. Identify the target pattern. 3. Combine using the "Best Trick" (Ignore|Match|(Capture)). 4. Optimize using AGRA (Anchor, Greed, Repeat, Atomic).
Detailed Regexp Guide
What is the "Best Regex Trick Ever"?
MiddleAnswer: It is a technique to match patterns while excluding specific contexts (like quotes or comments) using a simple Ignore|Match|(Capture) pattern.
Detailed Regexp Guide
What is preg_filter?
Middle
Answer: It is similar to preg_replace, but it only returns the elements that actually matched the pattern, effectively filtering the input array.
Detailed Regexp Guide
What are Atomic Groups and why use them?
SeniorAnswer: (?>...) groups prevent backtracking. They "lock" a match, preventing the engine from trying alternative paths, which avoids "catastrophic backtracking" and improves performance.
Detailed Regexp Guide
Is ChatGPT good at regex?
SeniorAnswer: While helpful for drafts, ChatGPT often lacks deep expertise. It can produce "dot-star soup" (inefficient patterns) or make syntax errors. Expert review is always needed. Detailed Regexp Guide