带有特殊字符的 Strpos 意外结果

Strpos unexpected result with special characters

我正在尝试在 HTML 文档中找到 HTML 元素 的位置。 所以我这样做:

    $filestring = file_get_contents($filename); //get the raw file
    $filestring = htmlspecialchars($filestring);

   $pos = strpos($filestring, "<head>"); //find the position of <head>
   print_r($pos); //print the position

结束print_r不要什么都不显示。我觉得是特殊字符的缘故,但是不明白怎么办。

为什么使用htmlspecialchars? 您是否了解使用此函数会导致所有实体(如 >< 被它们的表示形式(如 &gt;&lt; 替换)?

所以,解决方案是

  • 要么不使用 htmlspecialchars
  • 或者不搜索 <head> 而搜索 &lt;head&gt;

$filestring 中没有 <head> 这样的东西。 当您使用 htmlspecialchars 时,<> 会被替换:

http://php.net/manual/en/function.htmlspecialchars.php

$pos = strpos($filestring, "&lt;head&gt;");

或者在搜索字符串时不要使用 htmlspecialchars

我认为你应该从你的代码中删除这一行。

$filestring = htmlspecialchars($filestring);