简体   繁体   English

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

[英]Search words by delimiter in PHP and put them into array

I have a string in PHP that contains this code:我在 PHP 中有一个包含以下代码的字符串:

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

This is stored in a database and I have a lot of them.这存储在数据库中,我有很多。 The variables between $ can be different in each record.每个记录中 $ 之间的变量可以不同。 I want to get the name of the variables and store them into an array, for example:我想获取变量的名称并将它们存储到一个数组中,例如:

array('username', 'email');

Thanks谢谢

EDIT: The document HTML is dynamic and stored in database, for example I can also have something like this:编辑:文档 HTML 是动态的并存储在数据库中,例如我也可以有这样的东西:

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

You can use preg_match_all function.您可以使用preg_match_all函数。

try below code:试试下面的代码:

$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);

Output输出

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

Please try the below code to extract the variables请尝试以下代码来提取变量

$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);

   ?>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM