I want to fetch text in array between all <span> </span>
tag from HTML, I have tried with this code but it returns only one occurrence :
preg_match('/<span>(.+?)<\/span>/is', $row['tbl_highlighted_icon_content'], $matches);
echo $matches[1];
My 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,
My code returns only one occurrence of span tag, but I want get all text from every span tag in HTML in the form of a php array.
you need to switch to preg_match_all function
Code
$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);
as you can see now array
is correctly populated so you can echo
all your matches
use preg_match_all()
it's the same, it will return all the occurrences in the $matches array
http://php.net/manual/en/function.preg-match-all.php
here is code to get all span value in array
$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);
you output will be
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
)
)
you can use o or 1 index
If you don't mind using a third-party component, I'd like to show you Symfony's DomCrawler component. It 's a very simple way to parse HTML/XHTML/XML files and navigate through the nodes.
You can even use CSS Selectors. Your code would be something like:
$crawler = new Crawler($html);
$spans = $crawler->filter("span");
echo $spans[1]->getText();;
You don't even need to have a full HTML/XML document, if you assign only the <span>...</span>
part of your code, it'll work fine.