如何用每个锚文本替换所有锚点。我的代码是
$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>
答案 0 :(得分:2)
试试这个
$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);
答案 1 :(得分:1)
没有正则表达式.....
<?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]);
答案 2 :(得分: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
答案 3 :(得分:0)
可以使用此代码:
正则表达式:
define('DB_SERVER','localhost'); define('DB_USERNAME','xxx'); define('DB_PASSWORD','yyy'); define('DB_NAME','fff'); $conn = mysqli_connect(DB_SERVER,DB_USERNAME,DB_PASSWORD,DB_NAME); foreach($unique_array as $supplier) { $urep[]=$supplier['rep_name']; $udate[]=$supplier['date']; $ucid[]=$supplier['cid']; $unique_arrayyy[] = array('rep_name'=>$supplier['rep_name'], 'date'=>$supplier['date']); } array_map(function ($var) { $fetch_gdd=mysqli_query($conn,"select * from grade"); echo mysqli_num_rows($fetch_gdd); exit; }, $unique_arrayyy);
/< a.*?>|<a.*?>|<\/a>/g
测试并显示示例匹配字:https://regex101.com/r/mgYjoB/1