我在工作中使用simple-html-dom。我想得到所有的PHP脚本(<?php ... ?>)的形式文件使用简单的html-dom。
如果我有一个包含以下代码的文件(名称: text.php):
<html>
<head>
<title>Title</title>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>那么我如何使用<?php echo "This is test Text"; ?> -html-dom从上面的代码文件中获得这个PHP脚本呢?
$html = file_get_html('text.php');
foreach($html->find('<?php') as $element) {
//Sonthing code ...
}我不能这样使用,还有别的选择吗?
发布于 2018-07-26 21:28:23
这里有一个使用正则表达式的解决方案。请注意,通常不建议使用正则表达式来解析HTML文件。也就是说,在这种情况下,它可能是可以的。
这将匹配PHP代码块的每个实例,并允许您输出(或执行其他任何您想要的)整个块(包括标记)或块中包含的代码。请参阅preg_match_all()的文档。
<?php
$string = <<<'NOW'
<html>
<head>
<title>Title</title>
<?php echo "something else"; ?>
</head>
<body>
<?php echo "This is test Text"; ?>
</body>
</html>
NOW;
preg_match_all("/\<\?php (.*) \?\>/", $string, $matches);
foreach($matches[0] as $index => $phpBlock)
{
echo "Full block: " . $phpBlock;
echo "\n\n";
echo "Command: " . $matches[1][$index];
echo "\n\n";
}DEMO
https://stackoverflow.com/questions/51539027
复制相似问题