![](/img/trans.png)
[英]PHP preg_replace link to get href and anchor text and concatenate it
[英]preg_replace href anchor with anchor text
如何用每个锚文本替换所有锚点。 我的代码是
$body='<p>The man was <a href="http://www.example.com/video/">dancing like a little boy</a> while all kids were watching ... </p>';
我希望结果是:
<p>The man was dancing like a little boy while all kids were watching ... </p>
我用了 :
$body= preg_replace('#<a href="https?://(?:.+\.)?ok.co.*?>.*?</a>#i', '$1', $body);
结果是:
<p>The man was while all kids were watching ... </p>
试试这个
$body='<p>The man was <a href="http://www.example.com/video/">dancing like a little boy</a> while all kids were watching ... </p>';
echo preg_replace('#<a.*?>([^>]*)</a>#i', '$1', $body);
没有正则表达式......
<?php
$d = new DOMDocument();
$d->loadHTML('<p>The man was <a href="http://www.example.com/video/">dancing like a little boy</a> while all kids were watching ... </p>');
$x = new DOMXPath($d);
foreach($x->query('//a') as $anchor){
$url = $anchor->getAttribute('href');
$domain = parse_url($url,PHP_URL_HOST);
if($domain == 'www.example.com'){
$anchor->parentNode->replaceChild(new DOMText($anchor->textContent),$anchor);
}
}
function get_inner_html( $node ) {
$innerHTML= '';
$children = $node->childNodes;
foreach ($children as $child) {
$innerHTML .= $child->ownerDocument->saveXML( $child );
}
return $innerHTML;
}
echo get_inner_html($x->query('//body')[0]);
你可以在这里使用strip_tags()和htmlspecialchars() 。
strip_tags - 从字符串中删除 HTML和PHP标记
htmlspecialchars - 将特殊字符转换为HTML实体
步骤1:使用strip_tags()去除除<p>
标记之外的所有标记。
第2步:由于我们需要获取字符串以及HTML标记,因此我们需要使用htmlspecialchars() 。
echo htmlspecialchars(strip_tags($body, '<p>'));
当已经有一个内置的PHP函数时,我认为使用它而不是使用preg_replace
更好更紧凑
可以使用此代码:
正则表达式:
/< a.*?>|<a.*?>|<\\/a>/g
$body='<p>The man was <a href="http://www.example.com/video/">dancing like a little boy</a> while all kids were watching ... </p>';
echo preg_replace('/< a.*?>|<a.*?>|<\/a>/', ' ', $body);
测试并显示示例匹配字: https : //regex101.com/r/mgYjoB/1
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.