提取 php 字符串中以 $ 开头的单词

Extracting the words starting with $ in the string in php

本文关键字:开头 单词 php 字符串 提取      更新时间:2023-09-26

我想对文本区域内容中以字符 $ 开头的单词进行分组。这是编辑器内容。示例参数:

嗨$firstname,请找到下面提到的公司凭据:员工姓名:员工编号:员工用户名:$username电子邮件 ID: $email密码:$password问候行政团队   

我的代码:

$pattern = '/([$])'w+/';
preg_match($pattern, $input, $matches);
print_r($matches);

输出为 :

Array (
    [0] => $firstname 
    [1] => $ 
) 

我需要输出为:

Array (
    [0] => $firstname 
    [1] => $username 
    [2]=>$email 
    [3]=>$password
)

我做错了什么?

$matches = array();
preg_match_all('/'$'w+/', $text, $matches);
print_r($matches);

你需要使用 preg_match_all . preg_match仅返回第一个匹配项。此外,修复您的正则表达式以匹配实际文本:

$pattern = '/[$]('w+)/';
preg_match_all($pattern, $input, $matches);
foreach($matches as $match) {
    echo $match[0] . ': ' . $match[1];
}

这将输出:

$firstname : firstname
$username : username
$email : email
$password : password