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

如何使用PHP preg_match_all函数提取字符串中的用户名和密码值并生成新数组

Got it, let’s walk through how to do this with PHP’s preg_match_all — it’s straightforward once you nail the right regex pattern. I’ll cover common scenarios since you didn’t share your exact input string, but you can tweak the regex to fit your specific format!

Step 1: Start with your input string

First, let’s use a couple of sample strings to demonstrate. For example, a plain text key-value string:

$input = "Account Details: Username=maria_lee; Password=MyP@ss123; Email=maria@example.com";

Or an HTML snippet with credentials:

$input = "<div class='login-data'><p>Username: bob_brown</p><p>Password: B0b$Pass</p></div>";

Step 2: Write the regex and use preg_match_all

The core is crafting a regex that captures the values tied to "Username" and "Password". Here’s how to do it for common cases:

Case 1: Plain key-value pairs (with = or : separators)

This regex matches either label, skips any whitespace, then captures the value until a common separator (like ;, comma, or space):

$pattern = '/Username[:=]\s*([^;,\s]+)|Password[:=]\s*([^;,\s]+)/i';

// Use PREG_SET_ORDER to group matches by each hit
preg_match_all($pattern, $input, $matches, PREG_SET_ORDER);

// Convert matches into a clean associative array
$credentials = [];
foreach ($matches as $match) {
    if (!empty($match[1])) {
        $credentials['Username'] = $match[1];
    }
    if (!empty($match[2])) {
        $credentials['Password'] = $match[2];
    }
}

// Check the result
print_r($credentials);

Running this with the first sample input will output:

Array
(
    [Username] => maria_lee
    [Password] => MyP@ss123
)

Case 2: HTML or labeled text

If your string has HTML elements or plain labels followed by text, adjust the regex to capture everything until the next tag or line break:

$pattern = '/Username:\s*([^<\n]+)|Password:\s*([^<\n]+)/i';

preg_match_all($pattern, $input, $matches, PREG_SET_ORDER);

$credentials = [];
foreach ($matches as $match) {
    // Use trim() to clean up extra whitespace
    if (!empty($match[1])) {
        $credentials['Username'] = trim($match[1]);
    }
    if (!empty($match[2])) {
        $credentials['Password'] = trim($match[2]);
    }
}

print_r($credentials);

Step 3: Tweak for your specific format

If your input is something like JSON or XML, regex might not be the best tool (use json_decode() or SimpleXML instead), but if you need regex:

  • For JSON: /\"Username\"\s*:\s*\"([^\"]+)\"|\"Password\"\s*:\s*\"([^\"]+)\"/
  • For XML: /<Username>([^<]+)<\/Username>|<Password>([^<]+)<\/Password>/

Pro Tips

  • The i modifier makes the regex case-insensitive, so it works with "username", "USERNAME", etc.
  • If your password includes spaces or special characters like ;, adjust the capture group (e.g., use ([^;]+) instead of ([^;,\s]+) to allow spaces).
  • Always test your regex with your actual input to make sure it captures the values correctly.

That’s it! Let me know if you need help adjusting this to your exact string.

内容的提问来源于stack exchange,提问作者Ray Lian

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.05.19 04:04:21