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.

Kaleem Sajid
  • 230
  • 1
  • 2
  • 13
  • 2
    Have a look at http://stackoverflow.com/questions/3577641/how-to-parse-and-process-html-with-php – Clive Sep 09 '12 at 13:26

3 Answers3

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;
Tchoupi
  • 14,560
  • 5
  • 37
  • 71
Shail
  • 1,565
  • 11
  • 24
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.

moopet
  • 6,014
  • 1
  • 29
  • 36
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);
}
Evert S
  • 19
  • 2