<p>
文字列内のタグを見つける必要があります。次に、からの文字列を保存したい(含む)
別の変数にタグ付けします。
たとえば、私は文字列名firstStringを持っています。
firstString ="<div id='tab-1'><p>This is first string</p></div>"
2番目の文字列を
secondString ="<p>This is first string</p>"
最初の<p>
タグだけが必要です。
<p>
文字列内のタグを見つける必要があります。次に、からの文字列を保存したい(含む)
別の変数にタグ付けします。
たとえば、私は文字列名firstStringを持っています。
firstString ="<div id='tab-1'><p>This is first string</p></div>"
2番目の文字列を
secondString ="<p>This is first string</p>"
最初の<p>
タグだけが必要です。
DOMDocument::loadHTML
. 最速のオプションではないかもしれませんが、シンプルにする必要があります。
$dom = new DOMDocument();
$dom->loadHTML($str);
$xp = new DOMXPath($dom);
$res = $xp->query('//p');
$firstParagraph = $res[0]->nodeValue;
単純な正規表現を使用して、この部分文字列を取得できます。
$firstString = "<div id='tab-1'><p>This is first string</p></div>";
preg_match("#(<p>.+</p>)#", $firstString, $out);
echo $out[1];
文字列がどのように形成されるかをより正確に知っている場合、または代わりに使用できる複数の部分文字列を引き出したい場合は、他の方法がありますpreg_match_all
。
ただし、これが一般的にHTML から何かをスクレイピングするためのものである場合は、DOMDocument などの専用システムを使用する必要があります。
/* 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);
}