Reputation: 230
I need to find <p>
tag inside a string. Then I want to store the string from (including)
tag into another variable.
For example I have string name firstString;
firstString = "<div id='tab-1'><p>This is first string</p></div>"
I want second string to be
secondString = "<p>This is first string</p>"
I need only first <p>
tag.
Upvotes: 1
Views: 302
Reputation: 19
/* find opening tag */
$strPosBegin = strstr($firstString,"<p>");
if $strPosBegin != 0 {
/* find position of closing tag */
$strPosEnd = strstr($firstString,"</p>");
/* adjust for the length of closing tag */
$strPosEnd = $strPosEnd + 3;
/* calculate difference, but need to add 1 */
$strLength = $strPosEnd - $strPosBegin + 1;
/* use substr to lift your search string out of $firstString
$secondString = substr($firstString, $strPosBegin, $strLength);
}
Upvotes: 0
Reputation: 1575
DOMDocument::loadHTML
. Maybe not the fastest option, but should be simple.
$dom = new DOMDocument();
$dom->loadHTML($str);
$xp = new DOMXPath($dom);
$res = $xp->query('//p');
$firstParagraph = $res[0]->nodeValue;
Upvotes: 6
Reputation: 6185
You can use a simple regex to grab this substring.
$firstString = "<div id='tab-1'><p>This is first string</p></div>";
preg_match("#(<p>.+</p>)#", $firstString, $out);
echo $out[1];
There are other ways to do it if you know more precisely how the string is formed, or if you wish to pull out multiple substrings you can use preg_match_all
instead.
If this is for scraping something from HTML in general though, you should be using a dedicated system like DOMDocument.
Upvotes: 0