加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 站长学院 > PHP教程 > 正文

在PHP中查找多个字符串位置

发布时间:2020-12-13 13:46:04 所属栏目:PHP教程 来源:网络整理
导读:我正在编写一个解析给定URL的 PHP??页面.我能做的只是找到第一次出现,但当我回应它时,我得到另一个值而不是给定的值. 这就是我到现在所做的. ?php$URL = @"my URL goes here";//get from database$str = file_get_contents($URL);$toFind = "string to find"
我正在编写一个解析给定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);
?>

我知道可以使用循环,但我不知道循环体的条件.

我怎样才能显示我需要的输出?

这是因为你在htmlspecialchars($str)上使用了strpos,但你在$str上使用了substr.

htmlspecialchars()将特殊字符转换为HTML实体.举一个小例子:

// search 'foo' in '&foobar'

$str = "&foobar";
$toFind = "foo";

// htmlspecialchars($str) gives you "&amp;foobar"
// as & is replaced by &amp;. 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,strlen($toFind)); // prints ar

要解决这个问题,请在两个函数中使用相同的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.
}

输出:

Found foo at position 1 Found foo at position 8

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读