获取 HTML 标签之间的文本 [英] Get text between HTML tags

查看:43
本文介绍了获取 HTML 标签之间的文本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的,我确定这是一个非常基本的问题,但我是 PHP 新手,一直无法弄清楚.输入字符串是 $data 我试图继续拉取并且只使用第一个匹配项.下面不正确吗?这甚至可能不是执行操作的最佳方式,我只是试图将内容拉入两个 html 标签(找到的第一组)并丢弃其余数据.我知道有类似的问题,我都阅读了它们,我的问题是一个混合问题,如果有更好的方法来做到这一点,以及我如何将匹配定义为其余代码的新输入.如果我将 $matches 更改为 $data2 并从那里开始使用它,它会返回错误.

Ok, This is a pretty basic question im sure but im new to PHP and haven't been able to figure it out. The input string is $data im trying to continue to pull and only use the first match. Is the below incorrect? This may not even be the best way to perform the action, im just trying to pull the contents in between two html tags (first set found) and discard the rest of the data. I know there are similar questions, ive read them all, my question is a mix, if theres a better way to do this and how i can define the match as the new input for the rest of the remaining code. If i change $matches to $data2 and use it from there on out it returns errors.

preg_match('/<h2>(.*?)<\/h2>/s', $data, $matches);

推荐答案

使用正则表达式通常是解决问题的好主意.

Using regular expressions is generally a good idea for your problem.

当您查看 http://php.net/preg_match 时,您会看到 $matches 将是一个数组,因为可能有不止一场比赛.试试

When you look at http://php.net/preg_match you see that $matches will be an array, since there may be more than one match. Try

print_r($matches);

了解结果的外观,然后选择正确的索引.

to get an idea of how the result looks, and then pick the right index.

如果有匹配,则可以用

print($matches[1]);

如果您有多个括号组,它们将被编号为 2、3 等.您还应该考虑没有匹配的情况,在这种情况下,数组的大小为 0.

If you had more than one parenthesis-group they would be numbered 2, 3 etc. You should also consider the case when there is no match, in which case the array will have the size of 0.

这篇关于获取 HTML 标签之间的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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