You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何使用PHP正则表达式提取指定字符串中的name值

How to Extract the 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 our name value.
  • We don't need substr anymore 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 (like name or age).
  • (?:}}<\/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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 06:42:53