10

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

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

4 回答 4

2

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

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

于 2013-04-15T12:56:48.830 回答
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所有匹配

于 2013-04-15T13:00:30.430 回答
1

这是获取数组中所有跨度值的代码

      $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 索引

于 2013-04-15T13:01:06.733 回答
0

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

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

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

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

于 2013-04-15T13:10:18.643 回答