在PHP中按分隔符搜索单词,并将它们放入数组中


Search words by delimiter in PHP and put them into array

我在PHP中有一个字符串,其中包含以下代码:

<html>
<head>
<body>
  <p>Hi! $username$, your email is $email$</p>
</body>
</head>
</html>

这存储在一个数据库中,我有很多。在每条记录中,$之间的变量可能不同。我想获得变量的名称并将它们存储到一个数组中,例如:

array('username', 'email');

感谢

编辑:文档HTML是动态的,存储在数据库中,例如,我也可以有这样的东西:

<span>Test of $user$ with the $test$ and $foo$ and also a $foo2$ var</span>

您可以使用preg_match_all函数。

尝试以下代码:

$html = '<html>
<head>
<body>
  <p>Hi! $username$, your email is $email$</p>
</body>
</head>
</html>';
preg_match_all("/''$(.*?)''$/", $html, $matches1);
$required_array = $matches1[1];
print_r($required_array);

输出

Array
(
    [0] => username
    [1] => email
)
$content  = "<html>
<head>
<body>
  <p>Hi! $username$, your email is $email$</p>
</body>
</head>
</html>";
$p = explode("$", $content  );
echo $p[2]; // username
echo $p[4]; // email
preg_match("/(?:Hi! )(.*)(?:, your email is )(.*)(?:<'/p>)/", $input_line, $output);

http://www.phpliveregex.com/p/ffb

请尝试以下代码提取变量

$string = '<html>
<head>
<body>
<p>Hi! $username$, your email is $email$</p>
</body>
</head>
</html>';
    $pat= '/'$('w*)'$/';
    preg_match_all($pat, $string, $pat_array);
   $first  =  $pat_array[1][0];
   $second =  $pat_array[1][1];
   $final_array =array($first,$second);
   ?>