Andre Felipe
Andre Felipe

Reputation: 169

Regular Expression to ignore a link text

I have the following code:

<p>&nbsp;<img src="spas01.jpg" alt="" width="630" height="480"></p>
<p style="text-align: right;"><a href="spas.html">Spas</a></p>
<p>My Site Content [...]</p>

I need a regular expression to get only the "My Site Content [...]". So, i need to ignore first image (and maybe other) and links.

Upvotes: 0

Views: 46

Answers (2)

Casimir et Hippolyte
Casimir et Hippolyte

Reputation: 89557

With DOMDocument and DOMXPath:

$html = <<<'EOD'
<p>&nbsp;<img src="spas01.jpg" alt="" width="630" height="480"></p>
<p style="text-align: right;"><a href="spas.html">Spas</a></p>
<p>My Site Content [...]</p>
EOD;

$dom = new DOMDocument;
$dom->loadHTML($html);

$xp = new DOMXPath($dom);
$query = '//p//text()[not(ancestor::a)]';

$textNodes = $xp->query($query);

foreach ($textNodes as $textNode) {
    echo $textNode->nodeValue . PHP_EOL;
}

Upvotes: 0

Ahosan Karim Asik
Ahosan Karim Asik

Reputation: 3299

Try This:
Use (?<=<p>)([^><]+)(?=</p>) or <p>\K([^><]+)(?=</p>)

Update

   $re = "@<p>\\K([^><]+)(?=</p>)@m"; 
$str = "<p>&nbsp;<img src=\"spas01.jpg\" alt=\"\" width=\"630\" height=\"480\"></p>\n<p style=\"text-align: right;\"><a href=\"spas.html\">Spas</a></p>\n<p>My Site Content [...]</p>"; 

preg_match_all($re, $str, $matches);

Demo

Upvotes: 1

Related Questions