用于preg_replace HTML注释的正则表达式和SVG文件中的空标记

时间:2014-04-08 14:53:11

标签: php html xml regex svg

当Illustrator导出SVG文件时,它不能很好地优化它们。它放在文件顶部附近的一个令人烦恼且毫无意义的事情是以下HTML注释:

<!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  -->

我还有多个带有ID的空组标签,如:

<g id="svgSteps">
</g>
<g id="svgBase">
</g>

现在,我正在尝试使用正则表达式和preg_replace编写一些PHP来删除这样的内容。 我是regex的新手,已经尝试过在stackoverflow上发布的一些解决方案,这对我来说无效。

对于我尝试的HTML评论:

$fileContent = file_get_contents('my_file');
$fileContent = preg_replace('/<!--(.|\s)*?-->/','',$fileContent);
file_put_contents('my_file',$fileContent);

哪个不起作用。当我尝试使用str_replace代替<!--时,我知道file_get_contentsfile_put_contents正在运行(没有权限问题)。

正确的正则表达式是什么:

  1. 查找以<!--开头并以-->结尾的HTML评论,其中包含空格,字母数字字符,句号,逗号,冒号和括号。

  2. 查找以<g开头并以</g>结尾的标记,这些标记可以包含id,但在标记内只有空格或任何内容。

3 个答案:

答案 0 :(得分:3)

    preg_replace("/((<g id=\".*\">)|(<g>))[\s]*(<\/g>)/",'',$fileContent)
    preg_replace("/(<!--)[\s\S]*(-->)/",'',$fileContent)

答案 1 :(得分:1)

试试这个:

$fileContent = preg_replace('#<!--.*?-->#s', '', $fileContent);
$fileContent = preg_replace('#<(\w+)(?:\s+[^>]+)?>\s*</\1>#s', '', $fileContent);

我是在两个单独的preg_replace指令中制作的,因此也会删除仅包含评论的标记。

答案 2 :(得分:1)

这似乎对我有用:

<?php
$fileContent = '<!-- Generator: Adobe Illustrator 17.1.0, SVG Export Plug-In . SVG Version: 6.00 Build 0)  --> asdlfhjlkasdjhfasdf asd <g id="kjkjkh" /> askdjghf ag <g id="eeee" > </g>ahsdjghakjhglkjdahlg';
$fileContent = preg_replace('/(<\!--(.|\s)*-->)?([\n\w\W]*)?/','$3',$fileContent);
$fileContent = preg_replace('/<[gG]?\s+[Ii][Dd]="?\w+"\s*(?:\/>|>)[\s\t]*(<\/[gG]>)?/', ' ',$fileContent);
echo($fileContent);
?>