PHP查找字符串中所有出现的子字符串 [英] PHP Find all occurrences of a substring in a string

查看:104
本文介绍了PHP查找字符串中所有出现的子字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要解析一个HTML文档并查找其中所有出现的字符串asdf.

I need to parse an HTML document and to find all occurrences of string asdf in it.

我目前已将HTML加载到字符串变量中.我只需要字符位置,这样我就可以遍历列表以在字符串之后返回一些数据.

I currently have the HTML loaded into a string variable. I would just like the character position so I can loop through the list to return some data after the string.

strpos函数仅返回 first 事件.返回全部 怎么样?

The strpos function only returns the first occurrence. How about returning all of them?

推荐答案

在不使用正则表达式的情况下,类似这样的方法应该可以返回字符串位置:

Without using regex, something like this should work for returning the string positions:

$html = "dddasdfdddasdffff";
$needle = "asdf";
$lastPos = 0;
$positions = array();

while (($lastPos = strpos($html, $needle, $lastPos))!== false) {
    $positions[] = $lastPos;
    $lastPos = $lastPos + strlen($needle);
}

// Displays 3 and 10
foreach ($positions as $value) {
    echo $value ."<br />";
}

这篇关于PHP查找字符串中所有出现的子字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆