假设我有以下文本:
..(content).............
<A HREF="http://foo.com/content" >blah blah blah </A>
...(continue content)...
我想删除链接并删除 `` 标签(同时保留中间的文本)。如何使用正则表达式来实现这一点(因为URL都不同)?
非常感谢。
假设我有以下文本:
..(content).............
<A HREF="http://foo.com/content" >blah blah blah </A>
...(continue content)...
preg_replace("/<.*?>/", "", $string);
这将仅删除<a>
标记:preg_replace("/<\\/?a(\\s+.*?>|>)/", "", $string);
<?php
//example to extract the innerText from all anchors in a string
include('simple_html_dom.php');
$html = str_get_html('<A HREF="http://foo.com/content" >blah blah blah </A><A HREF="http://foo.com/content" >blah blah blah </A>');
//print the text of each anchor
foreach($html->find('a') as $e) {
echo $e->innerText;
}
?>
$data = str_replace('</a>', '', $data);
$data = preg_replace('/<a[^>]+href[^>]+>/', '', $data);
strip_tags()
也可以使用。
请参见此处的示例。
strip_tag
函数,并且在这里复制代码示例并不必要;) 这个答案已经包含了函数名称及其链接参考。 - Wh1T3h4Ck5$pattern = '/href="([^"]*)"/';
我使用这个来将锚替换为文本字符串...
function replaceAnchorsWithText($data) {
$regex = '/(<a\s*'; // Start of anchor tag
$regex .= '(.*?)\s*'; // Any attributes or spaces that may or may not exist
$regex .= 'href=[\'"]+?\s*(?P<link>\S+)\s*[\'"]+?'; // Grab the link
$regex .= '\s*(.*?)\s*>\s*'; // Any attributes or spaces that may or may not exist before closing tag
$regex .= '(?P<name>\S+)'; // Grab the name
$regex .= '\s*<\/a>)/i'; // Any number of spaces between the closing anchor tag (case insensitive)
if (is_array($data)) {
// This is what will replace the link (modify to you liking)
$data = "{$data['name']}({$data['link']})";
}
return preg_replace_callback($regex, array('self', 'replaceAnchorsWithText'), $data);
}