如何使用PHP正则表达式提取指定字符串中的name值
name Value with Regex in PHP Hey there! Let's work through this to get that name value extracted cleanly. Your current approach uses substr which works for this specific case, but it's not very flexible if your template syntax ever changes. Instead, we can use regex capture groups to directly grab the value we want—way more reliable!
Option 1: Target the Exact <p>{{name}}</p> Structure
If you only need to handle this specific HTML template format, we can simplify the regex to directly capture the word inside the {{...}} tags within the <p> element:
$subject = "<p>{{name}}</p>"; // Regex that matches the full <p>{{...}}</p> and captures the inner word $pattern = "/<p>{{(\w+)}}<\/p>/"; $success = preg_match($pattern, $subject, $match); if ($success) { echo $match[1]; // Outputs: name } else { echo 'not match'; }
Why this works:
(\w+)is a capture group that grabs one or more word characters (letters, numbers, underscores)—this is exactly ournamevalue.- We don't need
substranymore because the capture group directly gives us the content we care about, no hardcoded offsets required.
Option 2: Support Both <p>{{...}}</p> and [[...]] Formats
Your original regex tried to handle two template syntaxes. Let's refine that to capture the value consistently across both cases:
$subject1 = "<p>{{name}}</p>"; $subject2 = "[[age]]"; // Regex that matches either syntax and captures the inner value $pattern = "/(?:<p>{{|\[\[)(\w+)(?:}}<\/p>|]])/"; // Test first subject if (preg_match($pattern, $subject1, $match)) { echo $match[1]; // Outputs: name } // Test second subject if (preg_match($pattern, $subject2, $match)) { echo $match[1]; // Outputs: age }
Breakdown of the regex:
(?:<p>{{|\[\[): A non-capturing group that matches either<p>{{or[[(the?:means we don't store this part in our matches).(\w+): Our capture group for the actual value (likenameorage).(?:}}<\/p>|]]): Another non-capturing group that matches the closing part of either syntax.
Key Takeaway
Using capture groups is always better than substr for regex extraction because it's resilient to changes in your template tags. If you ever modify the surrounding HTML or syntax, you only need to adjust the regex's non-capturing parts—your target value stays in the same capture group.
内容的提问来源于stack exchange,提问作者somesh

