如何从字符串中删除第一个链接?

时间:2009-11-07 01:07:56

标签: php

如何使用PHP从此文本中删除带有图像的第一个链接?

<a href="some link"><img src="image link" /></a>Lorem ipsum dolor sit amet, consectetur adipiscing elit.** 

3 个答案:

答案 0 :(得分:3)

$str = '<a href="some link"><img src="image link"></a>Lorem ipsum dolor sit amet, consectetur adipiscing elit.<a href="some link"><img src="image link"></a>';

// strip the entire <a> tag including contents (first occurrence only)
$str = preg_replace('/<a.*?<\/a>/', '', $str, 1); 

// strip only the <a> leaving the inner HTML (first occurrence only)
$str = preg_replace('/<a[^>]*>(.*?)<\/a>/', '$1', $str, 1);

答案 1 :(得分:1)

我首先将'&gt;'拆分为行字符..

PHP:

$line = "<a href=''><img src=''></a>blah blah blah";
$parts = explode('>', $line);

如果你想要图片......

$img = $parts[1].">";

如果您只想要文字......

$text = $parts[3];

答案 2 :(得分:1)

$doc = DOMDocument::loadHTML($html);
$link = $doc->getElementsByTagName('a')->item(0);
$link->parentNode->removeChild($link);
$html = $doc->saveHTML();