如何从HTML获取位于所有<span&>标记之间的数组中的文本?

2022-03-29 00:00:00 php preg-match preg-match-all

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

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标记的所有文本。


解决方案

您需要切换到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所有匹配项

相关文章