Skip to content
Advertisement

PHP get the content after each h2 tag

I’m trying to use php to extract content after each h2 tag (and before the next h2 tag)..

Example:

JavaScript

To become

JavaScript

I have tried so many different things, too many to list here. I only want to extract the content between the h2 tags, not the h2 tags themselves.

If anyone could please point me in the right direction, or help me out, that would be greatly appreciated!

Thank you.

Advertisement

Answer

Try this one 🙂

JavaScript

Demo -> https://www.phpliveregex.com/p/x7j (select, preg_match_all)

Edit

Note, if you ask yourself why there is an multidimensional array as match result:

  • $matches[0] is an array of full pattern matches

  • $matches[1] is an array of strings matched by the first parenthesized subpattern.

  • $matches[2] is an array of strings matched by the second parenthesized subpattern.

  • (…), and so on

If you want to check if the preg_match_all was successful note to check $match[0] before you proceed. If you want to check you match groups note to check eg. $1 -> $match[1], $2 -> $match[2], $3 -> $match[3], (…) and so on;

If you match multiple times your match groups will contain more than one result.

Example: single match

https://phpsandbox.io/n/icy-term-9wp6

JavaScript

Example: multiple match

https://phpsandbox.io/n/shy-credit-0ng6

JavaScript

Example: handle error

https://phpsandbox.io/n/bitter-morning-55gn

JavaScript

See php.net docs -> https://www.php.net/manual/en/function.preg-match-all.php

User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement