PHP Preg_match匹配一个类并获取内容

时间:2022-11-28 22:05:48
$str = '<div class="rss"><img src="http://www.wired.com/images_blogs/gadgetlab/2013/10/1125_hbogo_660-660x436.jpg" alt="You Can Now Get HBO GO Without Paying for Other Channels">
</div>Fans of';

I'm trying to get hold of the text after the <div class="rss"></div> but each expression I use doesn't seem to work.

我试图在

之后获取文本,但我使用的每个表达式似乎都不起作用。

matching .rss

if(preg_match('/^(<div class=\"rss\">[\S\s]+?</div>([\S\s]*)$/i', $item_content, $matches)) { 

Could someone please help with this expression?

有人可以帮助这个表达吗?

Originally I had this expression to match an image tag instead of a div and this worked fine by using

最初我有这个表达式匹配图像标签而不是div,这通过使用工作得很好

if(preg_match('/^(<img[\S\s]+?>)([\S\s]*)$/i', $item_content, $matches)) {

2 个解决方案

#1


1  

I didn't go deeply for the regex but yours work well with just solving some syntax problems.

我没有深入研究正则表达式,但是你只需解决一些语法问题就可以了。

It should be:

它应该是:

^<div class=\"rss\">[\S\s]+?<\/div>([\S\s]*)$/i

Live demo

#2


0  

This may help:

这可能有所帮助:

<?php
$item_content = '<div class="rss"><img src="http://www.wired.com/images_blogs/gadgetlab/2013/10/1125_hbogo_660-660x436.jpg" alt="You Can Now Get HBO GO Without Paying for Other Channels">
</div>Fans of';

if(preg_match('/^(<div class=\"rss\">[\S\s]+?<\/div>)([\S\s]*)$/i', $item_content, $matches)) {
  $div = $matches[1];
  $text = $matches[2];

  echo "<textarea style=\"width: 600px; height: 300px;\">";
  echo $div . "\n";
  echo $text . "\n";
  echo "</textarea>";
}
?>

#1


1  

I didn't go deeply for the regex but yours work well with just solving some syntax problems.

我没有深入研究正则表达式,但是你只需解决一些语法问题就可以了。

It should be:

它应该是:

^<div class=\"rss\">[\S\s]+?<\/div>([\S\s]*)$/i

Live demo

#2


0  

This may help:

这可能有所帮助:

<?php
$item_content = '<div class="rss"><img src="http://www.wired.com/images_blogs/gadgetlab/2013/10/1125_hbogo_660-660x436.jpg" alt="You Can Now Get HBO GO Without Paying for Other Channels">
</div>Fans of';

if(preg_match('/^(<div class=\"rss\">[\S\s]+?<\/div>)([\S\s]*)$/i', $item_content, $matches)) {
  $div = $matches[1];
  $text = $matches[2];

  echo "<textarea style=\"width: 600px; height: 300px;\">";
  echo $div . "\n";
  echo $text . "\n";
  echo "</textarea>";
}
?>