我想在数组中检索我的html页面的所有以$开头的单词。
网页内容测试.html
<p>{$Nom}</p>
<p>{$Prenom}</p>
<p>{$Adresse}</p>
<p>{$CP}</p>
<p>{$Ville}</p>
函数 PHP
$filename = "test.html";
$handle = fopen($filename, "r");
$input = fread($handle, filesize($filename));
$pattern = '/[$](w+)/';
$matches = array();
preg_match_all('/$w+/', $input, $matches);
print_r($matches);
显示的结果
数组 ( [0] => 数组 ( [0] => $NOM [1] => $PRENOM [2] => $ADRESSE [3] => $CP [4] => $VILLE [5] => ) )
重复的预期结果:
名词普雷诺姆阿德雷斯正中电维尔
实际上,有一种比按照 Ray 告诉你的去做更简单的方法。您可以
$filename = "test.html";
$handle = fopen($filename, "r");
$input = fread($handle, filesize($filename));
$matches = array();
// see the important part is wrapping the w+ inside ( )
preg_match_all('/$(w+)/', $input, $matches);
print_r($matches);
因为在正则表达式中用 () 包装某些东西实际上会返回另一个包含该匹配部分的数组。因此,将返回另一个数组,其中包含字符串的 (\w+) 部分,即仅表示单词。所以现在上面将输出
Array
(
[0] => Array
(
[0] => $Nom
[1] => $Prenom
[2] => $Adresse
[3] => $CP
[4] => $Ville
)
[1] => Array
(
[0] => Nom
[1] => Prenom
[2] => Adresse
[3] => CP
[4] => Ville
)
)
但不要忘记,您现在需要$matches[1]
当然,只需执行以下操作,因为您需要它们在数组中
<?php
$filename = "test.html";
$handle = fopen($filename, "r");
$input = fread($handle, filesize($filename));
$pattern = '/[$](w+)/';
$matches = array();
preg_match_all('/$w+/', $input, $matches);
$final_result = array();
$index=0;
foreach($matches as $match){
$final_result[$index] = str_replace('$','',$match[$index]);
$index++;
}