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

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

问题描述

好吧,这是一个pretty基本问题,我敢肯定,但即时通讯新到PHP,并一直没能弄明白。输入字符串为$的数据我尝试继续拉,只使用第一个匹配。是下面不正确的?这可能甚至不执行的操作的最佳方式,即时通讯只是想拉内容两者之间的html标签(第一组发现),丢弃该数据的其余部分。我知道有类似的问题,香港专业教育学院读他们,我的问题是混合,如果theres一个更好的方式来做到这一点,我怎么能定义匹配至于其余code其余部分的新的输入。如果我改变$场比赛,$数据2,并用它从那里出来它会返回错误。

  preg_match('/< H2方式>?(*)< \\ / H&GT / s之间',$数据,$匹配);


解决方案

使用常规的前pressions通常是你的问题是一个好主意。

当你看到 http://php.net/$p$pg_match 你看到$的比赛将是一个阵,因为可能有多个匹配。尝试

 的print_r($比赛);

得到的结果看起来如何的想法,然后再挑选合适的索引。

编辑:

如果有匹配,那么你可以得到的括号组之间提取的文本以

 打印($匹配[1]);

如果你有一个以上的括号组,他们将被编号为2,3等,还应该考虑当没有匹配,在这种情况下,阵列将有0的大小。

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.

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.

EDIT:

If there is a match, then you can get the text extracted between the parenthesis-group with

print($matches[1]);

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天全站免登陆