如何在HTML中的所有<span>标记之间获取数组中的文本?</span>

时间:2013-04-15 12:53:33

标签: php preg-match preg-match-all

我想在HTML中的所有<span> </span>标记之间获取数组中的文本,我尝试使用此代码,但只返回一次:<​​/ p>

preg_match('/<span>(.+?)<\/span>/is', $row['tbl_highlighted_icon_content'], $matches);

echo $matches[1]; 

我的HTML:

<span>The wish to</span> be unfairly treated is a compromise attempt that would COMBINE attack <span>and innocen</span>ce.  Who can combine the wholly incompatible, and make a unity  of what can NEVER j<span>oin? Walk </span>you the gentle way,

我的代码只返回一次span标记,但我希望以php数组的形式从HTML中的每个span标记中获取所有文本。

4 个答案:

答案 0 :(得分:2)

使用preg_match_all()它是相同的,它将返回$ matches数组中的所有匹配项

http://php.net/manual/en/function.preg-match-all.php

答案 1 :(得分:2)

您需要切换到preg_match_all功能

$row['tbl_highlighted_icon_content'] = '<span>The wish to</span> be unfairly treated is a compromise attempt that would COMBINE attack <span>and innocen</span>ce. Who can combine the wholly incompatible, and make a unity of what can NEVER j<span>oin? Walk </span>you the gentle way,';    

preg_match_all('/<span>.*?<\/span>/is', $row['tbl_highlighted_icon_content'], $matches);

var_dump($matches);

您现在可以看到array已正确填充,因此您可echo所有匹配

答案 2 :(得分:1)

这里是获取数组

中所有span值的代码
      $str = "<span>The wish to</span> be unfairly treated is a compromise
attempt that would COMBINE attack <span>and innocen</span>ce. 
Who can combine the wholly incompatible, and make a unity 
of what can NEVER j<span>oin? Walk </span>you the gentle way,";

preg_match_all("/<span>(.+?)<\/span>/is", $str, $matches);


echo "<pre>";
print_r($matches);

您的输出将是

Array
(
    [0] => Array
        (
            [0] => The wish to
            [1] => and innocen
            [2] => oin? Walk 
        )

    [1] => Array
        (
            [0] => The wish to
            [1] => and innocen
            [2] => oin? Walk 
        )

)

你可以使用o或1索引

答案 3 :(得分:0)

如果您不介意使用第三方组件,我想向您展示Symfony's DomCrawler组件。这是解析HTML / XHTML / XML文件并在节点中导航的一种非常简单的方法。

您甚至可以使用CSS选择器。您的代码将类似于:

$crawler = new Crawler($html);
$spans = $crawler->filter("span");
echo $spans[1]->getText();;

您甚至不需要拥有完整的HTML / XML文档,如果只分配代码的<span>...</span>部分,它就可以正常工作。