-->

How to get text in array between all tag fr

2020-08-19 02:05发布

问题:

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.

回答1:

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



回答2:

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



回答3:

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



回答4:

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.