我在我的HTML文件正则表达式来解析模板块HTML
<!-- BEGIN user_details -->
<h1>{firstname} {lastname}</h1>
<!-- FINISH user_details -->
user_details
以上下列嵌段是含有像这样的数据的数组:
$user_details = array(
0 => array('firstname' => 'Hercules', 'lastname' => 'Zeus'),
1 => array('firstname' => 'Jesus', 'lastname' => 'Christ'),
2 => array('firstname' => 'John', 'lastname' => 'Smith'),
3 => array('firstname' => 'Goerge', 'lastname' => 'Bush')
);
存在与其他块不同的BEGIN/FINSIH数组名称和不同的{元素}所以,我需要一个正则表达式,它将遍历整个文件并查找像这样的块,然后遍历每个值并将其替换为实际值...
我最后的输出应该是:
<!-- user_details -->
<h1>Hercules Zeus</h1>
<h1>Jesus Christ</h1>
<h1>John Smith</h1>
<h1>George Bush</h1>
<!-- /userdetails -->
的<h1>…</h1>
标签是不固定的,在一些块我用<li></li>
等
我现在有这样的代码:
$search_in = file_get_contents('path/to/my/html/file/');
$search_for = "#<!-- BEGIN (.*?) -->(.+?)<!-- FINISH (.*?) -->#si";
if (!preg_match($search_for, $search_in, $return)) {
return NULL;
}
$return = preg_replace("#<!-- BEGIN (.*?) -->", "", $return[0]);
$return = preg_replace("<!-- FINISH (.*?) -->#si", "", $return);
return var_dump($return);
//Look for anything enclosed in curly brackes like so {something}
if(!preg_match_all("/{([^}]*)}/", $search_in, $matches)) {
return NULL;
}
//Return all occurrences of {something} in an array for use later
foreach($matches[0] as $value) {
$_args[] = $value;
}
但第一个不是var_dump
的任何数据,只有NULL
,而且我知道上面的所有内容都是有效的数据。我得到这些错误:
Notice: Undefined index: firstname in /home/content/v/i/r... on line 96 Notice: Undefined index: lastname in /home/content/v/i/r... on line 96
我不想使用像codeIgniter,cakePHP,Zend或类似的框架。
如果可能,请勿使用正则表达式。当然,有一个HTML解析库,可以通过元素进行导航。 – user2864740
此外,user2864740,我自定义了我的块,所以我需要知道自己该怎么做,而我对DDM,smarty或类似项目不感兴趣,他们的文件太大我只需要几个函数 – JiggaJitsu
我的意思是DOM上面不是DDM – JiggaJitsu