PHP正则表达式删除标记中的所有内容
我有一个包含锚定标签的字符串。这些锚定标记包含一些html和文本,如下所示:PHP正则表达式删除标记中的所有内容,php,regex,string,anchor,Php,Regex,String,Anchor,我有一个包含锚定标签的字符串。这些锚定标记包含一些html和文本,如下所示: <a class="content-title-link" title="Blog" href="https://example.com/my-blog" target="_blank"> <img id="my_main_pic" class="content-title-main-pic" src="https://example.com/xyz.jpg" width="30px" height
<a class="content-title-link" title="Blog" href="https://example.com/my-blog" target="_blank">
<img id="my_main_pic" class="content-title-main-pic" src="https://example.com/xyz.jpg" width="30px" height="30px" alt="Main Profile Picture">
My HTML Link
<label>Click here to view
<cite class="glyphicon glyphicon-new-window" title="Blog"></cite>
</label>
</a>
有人知道有没有可能做到这一点。我们可以尝试使用正则表达式。用捕获组替换以下模式:
<a.*?href="([^"]*)".*?>.*?<\/a>
请仔细注意/pattern/s
末尾的s
标志。这将在点全部模式下进行替换,这意味着点也将匹配换行符(即跨行,这是您想要的)
搜索此正则表达式:
<a.*?href="([^"]*)"[^>]*>
您好,提姆,请在我的问题中考虑带有内容的整个锚标签,以替换字符串中的“代码> <代码>和<代码> <代码>。@ GokulsHune我已经考虑到了这一点。你看过我提供的演示链接了吗?看过。我试过了,但没有为我工作。让我编辑一下问题,让它更清楚。@GokulShinde更新了答案。我做了两个改变。一个是将整个锚定标记从
匹配到
,另一个是在DOT ALL模式下进行替换/s
。
$dom = new DomDocument();
$dom->loadHTML( $text );
$matches = array();
foreach ( $dom->getElementsByTagName('a') as $item ) {
$matches[] = array (
'a_tag' => $dom->saveHTML($item),
'href' => $item->getAttribute('href'),
'anchor_text' => $item->nodeValue
);
}
foreach( $matches as $match )
{
// Replace a tag by its href
$text = str_replace( $match['a_tag'], $match['href'], $text );
}
return $text;
<a.*?href="([^"]*)".*?>.*?<\/a>
$result = preg_replace('/<a.*?href="([^"]*)".*?>.*?<\/a>/s', '$1', $string);
<a.*?href="([^"]*)"[^>]*>
$1