【问题标题】:Removing Known Characters From End of String从字符串末尾删除已知字符
【发布时间】:2016-07-27 15:43:19
【问题描述】:

我正在使用 file_put_content() 编写一个 HTML 文件,但希望以后能够通过拉取当前文件内容并切断 html 的已知结尾来添加其他内容。

所以大致如下:

$close = '</body></html>';

$htmlFile = file_get_contents('someUrl');
$tmp = $htmlFile - $close;

file_put_contents('someUrl', $tmp.'New Content'.$close);

但既然不能只减去字符串,那如何从文件内容的末尾去掉已知的字符串呢?

【问题讨论】:

  • 如果您知道不需要的东西有多长,那么只需使用substr() 将其撕掉。
  • 如果您需要追加到 HTML 文档,即使它恰好在最后,使用 dom 解析器可能比字符串操作更好。

标签: php html


【解决方案1】:

substr 可用于从字符串末尾截断已知长度。但也许你应该确定你的字符串是否真的以你的后缀结尾。为此,您还可以使用substr

if (strtolower(substr($string, -strlen($suffix))) == strtolower($suffix)) {
    $string = substr($string, 0, -strlen($suffix));
}

如果case不起任何作用,可以省略strtolower

另一方面,您可以使用str_replace 注入您的内容:

$string = str_replace('</body>', $newContent . '</body>', $string);

也许,Manipulate HTML from php 也有帮助。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2011-03-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-07
    • 1970-01-01
    • 1970-01-01
    • 2010-11-05
    相关资源
    最近更新 更多