Php字符串处理


Php string processing

我需要在字符串中找到<p>标记。然后我想把

标记中的字符串(包括)存储到另一个变量中。

例如,我有字符串名称firstString;

firstString="<div id='tab-1'><p>This is first string</p></div>"

我希望第二个字符串是

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);
}