【问题标题】:SED command in PHP script (error expression #1, char 34: Invalid preceding regular expression)PHP 脚本中的 SED 命令(错误表达式 #1,字符 34:前面的正则表达式无效)
【发布时间】:2013-07-12 08:39:16
【问题描述】:

这段代码运行了几个星期,现在返回一个错误。关于发生了什么的任何建议?看来我正在解析的网站做了一些小的改动,导致我的解析器卡住了它......


想象文件test.html中的以下字符串(不带点)

... </script> <script type="text/javascript" src=" ...

所需的字符串转换

Replace <script type="text/javascript" with <tagkilled

使用以下php代码

    $file = "test.html";

    // Destroy javascript codetag
    $command='/bin/sed -ri \'s/<script type="text\/javascript"/<tagkilled/g\' '.str_replace(' ','\ ',$file);
    exec($command);

返回错误信息

/bin/sed: -e expression #1, char 34: Invalid preceding regular expression

旁注:运行 sed 4.2.1 2010 年 12 月在 Ubuntu 12.10 上。

【问题讨论】:

  • 您总是容易受到远程站点 HTML 中的更改的影响。 HTML 不是您可以在 (see here) 上使用正则表达式的东西。有关更强大的解决方案,请阅读 PHP 的 DOMDocument 类。
  • 上面的代码为通过 DOM 解析器解析的文档做准备。为了进入页面的脚本部分,我需要删除脚本标签。这正是代码的作用。

标签: php regex ubuntu sed


【解决方案1】:

这适用于 GNU ,尝试将 sed 的 s 命令中的斜杠替换为另一个字符:s#search#replace#[flags]

$ cat file
</script> <script type="text/javascript" src="

$ sed 's#<script type="text/javascript"#<tagkilled#g' file
</script> <tagkilled src="


这里不需要g


您不应使用正则表达式处理 和类似的文件格式。使用 工具。

【讨论】:

  • 另外,PHP 没有自己的某种 sub/repl 实用程序吗?每天都有一个关于使用来自phpsed 的问题。那是怎么回事!? ; -) 祝大家好运。
猜你喜欢
  • 2020-01-15
  • 1970-01-01
  • 2013-02-02
  • 1970-01-01
  • 2012-10-29
  • 1970-01-01
  • 2013-08-07
  • 1970-01-01
相关资源
最近更新 更多