1

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.

1

3 Answers 3

6

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Fatal Error : Cannot use object of type DOMNodeList as array.
may be you can't access the DOMNodeList items with array-style syntax... you should instead use ->item(0).
Yeah.. It work.. Thank you Mathieu Imbert and Shail :) I used foreach loop. Also works with Shail's way.
0

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.

Comments

0
/* 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);
}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.