我正在编写一个解析给定URL的PHP页面.我能做的只是找到第一次出现,但当我回应它时,我得到另一个值而不是给定的值.
这就是我到现在所做的.
<?php
$URL = @"my URL goes here";//get from database
$str = file_get_contents($URL);
$toFind = "string to find";
$pos = strpos(htmlspecialchars($str),$toFind);
echo substr($str,$pos,strlen($toFind)) . "<br />";
$offset = $offset + strlen($toFind);
?>
Run Code Online (Sandbox Code Playgroud)
我知道可以使用循环,但我不知道循环体的条件.
我怎样才能显示我需要的输出?
cod*_*ict 17
这是因为您正在使用strpos的htmlspecialchars($str),但您使用substr上$str.
htmlspecialchars()将特殊字符转换为HTML实体.举一个小例子:
// search 'foo' in '&foobar'
$str = "&foobar";
$toFind = "foo";
// htmlspecialchars($str) gives you "&foobar"
// as & is replaced by &. strpos returns 5
$pos = strpos(htmlspecialchars($str),$toFind);
// now your try and extract 3 char starting at index 5!!! in the original
// string even though its 'foo' starts at index 1.
echo substr($str,$pos,strlen($toFind)); // prints ar
Run Code Online (Sandbox Code Playgroud)
要解决此问题,请在两个函数中使用相同的haystack.
为了回答你在其他问题中找到一个字符串的所有出现的其他问题,你可以使用第三个参数strpos,offset,它指定从哪里搜索.例:
$str = "&foobar&foobaz";
$toFind = "foo";
$start = 0;
while($pos = strpos(($str),$toFind,$start) !== false) {
echo 'Found '.$toFind.' at position '.$pos."\n";
$start = $pos+1; // start searching from next position.
}
Run Code Online (Sandbox Code Playgroud)
输出:
在位置1
找到foo在位置8找到foo
小智 5
使用:
while( ($pos = strpos(($str),$toFind,$start)) != false) {
Run Code Online (Sandbox Code Playgroud)
Explenation:)在false之后设置$start),因此$pos = strpos(($str),$toFind,$start)置于之间().
也使用!= false,因为php.net说:'这个函数可能返回布尔值FALSE,但也可能返回一个非布尔值,其值为FALSE,例如0或"".有关更多信息,请阅读有关布尔值的部分.使用===运算符测试此函数的返回值.