问题
Lets say that (in php) we have a variable which has text, links and images :
<a href="myimage_big"><img src="myimage.jpg" alt="pic" title="pic" border="0" /></a>
and we want to add to every a href tag the rel="light" as follow :
<a rel="lightbox" href="myimage_big"><img src="myimage.jpg" alt="pic" title="pic" border="0" /></a>
If the name of the variable is lets say $mydata then with str_replace we can do as follow to solve our problem :
$mydata = str_replace('<img ', '<img rel="lightbox"', $mydata);
Till here is all right, but what about the rest of the a href links that are not including any photo :
par example,
<a href="link1.php">link_no1</a>
<a href="link2.php">link_no2</a>
etc ? To this kind of links that are not including any image but text then with our str_replace code will also have a rel="lightbox" attribute that is not correct and i dont want :
<a rel="lightbox" href="link1.php">link_no1</a>
So how we can apply the rel="lightbox" only to the links that are including some image and to those links that are not including any image to dont set the rel="lightbox" attribute ..!?
回答1:
Does this regex solve the problem?
$str = '<a href="myimage_big"><img src="myimage.jpg" /></a>';
$str = preg_replace('~<a(?=[^>]+>\s*<img)~','<a rel="lightbox"',$str);
echo htmlspecialchars($str);
Using a lookahead to check, if the <a ...>
is followed by <img
回答2:
If you prefer to use a regular expression ...
$html = preg_replace('/(?<=<a)(?=[^>]*>[^<]*<img)/', ' rel="lightbox"', $html);
Although, I would consider using DOM and XPath ...
$doc = DOMDocument::loadHTML('
<a href="myimage_big"><img src="myimage.jpg" alt="pic" title="pic" border="0" /></a>
<a href="link1.php">link_no1</a>
<a href="link2.php">link_no2</a>
<a href="image.jpg"><img src="image1.jpg"></a>
');
$xpath = new DOMXPath($doc);
$links = $xpath->query('//a//img');
foreach($links as $link) {
$link->parentNode->setAttribute('rel', 'lightbox');
}
echo $doc->saveHTML();
来源:https://stackoverflow.com/questions/20767749/how-to-add-rel-lightbox-only-to-links-which-are-including-an-image-and-not-the