使用Python从HTML文件中删除PHP行

2024-09-25 08:38:57 发布

您现在位置:Python中文网/ 问答频道 /正文

我被要求从html文件中删除PHP。我相信我可以用Python实现这个过程的自动化,但是我仍然停留在多行PHP代码上。下面是一个PHP代码的示例。在

<?php 
  $seg = $this->uri->segment(2);
  $active_2 = '';$active_1 = '';$active_4 = ''; $active_3 = '';
  if($seg == "Enrichment"){
      $active_1 = 'class="active"';
  }
  elseif($seg == "Nightlife"){
     $active_2 = 'class="active"'; 
  }
  elseif($seg == "Misc"){
     $active_3 = 'class="active"'; 
  }
  else $active_4 = 'class="active"';
?>
<a class="" href="<?php echo base_url()?>"><div class="logo">Page Name</div></a>
<li><a href="<?php echo base_url()?>category/all" <?php echo $active_4?> onClick="_gaq.push(['_trackEvent','categories','All'])">All</a>

这是我的密码。如您所见,我不处理多行事件。我自己已经成功地提取了所有其他PHP事件,tho,所以我有了它。在

^{pr2}$

我尝试了几种不同的方法来解决多行问题,但都没有成功。如有任何建议或见解,我们将不胜感激。在


Tags: 代码echodivurlbasehtml事件all
3条回答

Best way is to use RE


示例:

import re

with open('php_file.txt', 'r') as f:
    html = re.sub('<\?.*?\?>', '', f.read(), re.MULTILINE)

with open('html_file.txt', 'w') as f:
    f.write(html)

不用排队。正则表达式确实值得研究:)

import re

php_file = open(filename, 'r').read()
html = re.sub('<\?.*?\?>', '', php_file, re.MULTILINE)

请注意regexp中的lazy syntax(即非贪婪)

不是最有效的例子,但给你一个开始:

k = 0
x = 0
ln = len(html)
ret = ''
while True:
    if html[x:x + 5] == '<?php':
        ret = '%s%s' % (ret, html[k:x])
        k = x
        x += 4
    if html[x:x + 2] == '?>':
        k = x + 2

    x += 1
    if x >= ln:
        ret = '%s%s' % (ret, html[k:])
        break

print(ret)

显然,您的源代码是html变量。请注意,这是不检查错误的:如果您忘记关闭php标记,结果与您的html/php源代码一样错误

相关问题 更多 >