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

时间:2014-12-04 13:34:45

标签: javascript php mysqli

我想从文本区域内容中分组以字符$开头的单词。这是编辑内容。 示例paragrraph:

Hi $firstname,

Please find the company credentials mentioned below:

Employee Name:
Employee ID:
Employee username: $username
Email ID: $email
Password: $password




Regards,
Administration Team    

我的代码:

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

输出是:

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

我需要输出:

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

我做错了什么?

2 个答案:

答案 0 :(得分:1)

您需要使用preg_match_allpreg_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

答案 1 :(得分:1)

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