0

I have div on index page and it is editable. Below div I have button for post. On click on button I send div content to another page called file.php Inside this file I have

$text = $_POST['text'];

Now I need somehow to check how many opening and closing spans I have inside $text

Example:

$text = "<span id='first'>first</span> some text <span id='second'>second</span> more text <span id='third'>third</span>";

Now foreach opened and closed span foreach span do something else... How can I check how many span I have in string and do foreach of them something else...

UPDATE: I tried this:

$html = str_get_html($text);
foreach($html->find('a') as $element){ 
       echo $element->href . '<br>';
}

And I get fatal error for undefined function in str_get_html

Cœur
  • 37,241
  • 25
  • 195
  • 267
Careless
  • 45
  • 1
  • 7
  • This might help [How to get span tag content using preg_match function](http://stackoverflow.com/a/18858627/5484276) – Amous Apr 26 '16 at 14:53
  • You should *never* parse HTML with regex. Use [a PHP DOM parser](http://simplehtmldom.sourceforge.net/) instead. – Jay Blanchard Apr 26 '16 at 15:01
  • @JayBlanchard I tried this: $html = str_get_html($text); foreach($html->find('a') as $element){ echo $element->href . '
    '; } But I get fatal error call to undefined function in str_get_html
    – Careless Apr 26 '16 at 15:13

1 Answers1

0

Try something like this:

$text = "<span id='first'>first</span> some text <span id='second'>second</span> more text <span id='third'>third</span>";

$dom = new DOMDocument;
$dom->loadHTML($text);
foreach( $dom->getElementsByTagName('span') as $node)
{
    echo $node->nodeValue . "<br/>"; 
}

Have a look at it here: PHP DOM: parsing a HTML list into an array?

Community
  • 1
  • 1
cdoshi
  • 23
  • 6