很抱歉这个问题已经在其他地方得到了回答。我仔细查看堆栈溢出,找不到我要找的东西。
我需要知道如何在一个目录中扫描多个php文件(例如test/),并在每个php文件的特定"标记"区域之间提取文本。
"标记"区域示例:
<?
/*
{('test1')}
*/
?>
<div>text here</div>
<?
/*
{('test2')}
*/
?>
代码将显示test1、test2等,并忽略其他任何内容。我试着查看fopen()、file_get_contents和preg_match_all,但每次它们都只找到第一个出现的"标记"区域,而不是每一个出现的区域。任何帮助都会很棒!
编辑-我目前拥有的:
foreach (glob("templates/*.php") as $fn) {
$file = file_get_contents($fn);
preg_match_all("#'{'('('w+)'')}#", $file, $matches);
$variable = join('', $matches[1]);
echo $variable.'<br />';
我如何将array_couck添加到其中,以便测试的每个迭代都作为自己的变量进行回显,而不是分组到一个数组中。我试过这个:
$variable = array_chunk($matches[1],1);
没有成功,它只是打印"阵列"。任何帮助都是伟大的事情。如果没有得到回复,我将发布一个新问题。
这就是如何转义正则表达式:
foreach (glob("template/*.php") as $fn) {
$file = file_get_contents($fn);
preg_match_all("#'{'('('w+)'')}#", $file, $matches);
print_r($matches);
}
Eugen已经展示了如何匹配PHP/PI <?
标记和/*
注释部分。您可能只需要介于两者之间的's*
。
$filepattern='test/*.php';
$tagpattern='/'<'?'n'/'*'n'{'(''([^'']+)''')'}'n'*'/'n'?'>/';
$files=glob($filepattern);
foreach ($files as $file) {
$content=file_get_contents($file);
$count=preg_match_all($tagpattern,$content,$matches);
if ($count<1) continue;
//Whatever you want to do with the matches!
foreach ($matches[1] as $match) echo "$file: $match'n";
}
Regex不适合并且速度较慢。试试php-dom或这个不错的库
http://simplehtmldom.sourceforge.net/