Get first HTML element from a string

html, php, selector, string

Solution

You could use http://php.net/strstr as the article

first search for `"<p>`" this will give you the full string from the first occurrence and to the end

$first = strstr($html, '<p>');

then search for "`</p>`" in that result, this will give you all the html you dont want to keep

$second = strstr($first, '</p>');

then remove the unwanted html

$final = str_replace($second, "", $first);

The same methode could be use to get the first child by looking for "`<`" and "`</$`" in the result from before. You will need to check the first char/word after the < to find the right end tag.

Problem

I was reading this article. This function that it includes: ``` <?php function getFirstPara($string){ $string = substr($string,0, strpos($string, "</p>")+4); return $string; } ?> ``` ...seems to return first found `<p>` in the string. But, how could I get the first HTML element (`p`, `a`, `div`, ...) in the string (kind of `:first-child` in CSS).

Original source