У меня есть такой сценарий.
$str = "this is a bet and he is <a href=''>Mansoon</a> and he please search on <a href='http://www.google.com'>Google</a> and say he <a href=''>Yammy</a>";
Я хочу удалить все теги href из строки с пустым href. Можете ли вы, пожалуйста, взглянуть на это.
Выход такой
$str = "this is a bet and he is Mansoon and he please search on <a href='http://www.google.com'>Google</a> and say he Yammy";
Большое спасибо
попробуйте это: обновите его, чтобы заполнить все случаи исключения:
$re = "/(<a[^href]*href=[\"']{2}[^>]*>)([^<>]*|.*)(<\\/a>)/m";
$str = "this is a bet and he is <a id=\"sss\" href='' dfsd fdg >Mansoon</a> and he please search on <a href='http://www.google.com'>Google</a> and say he <a href=''>Yammy</a> \n<a href=''> <i>Yammy </i> <br/> </a>\n\nthis is a bet and he is Mansoon and he please search on <a href='http://www.google.com'>Google</a> and say he Yammy";
$subst = "$2";
$result = preg_replace($re, $subst, $str);
href='"
или <a href=''><i>Yammy</i></a>
или другого html в href
.
Вы можете использовать:
$str = "this is a bet and he is <a href=''>Mansoon</a> and he please search on <a href='http://www.google.com'>Google</a> and say he <a href=''>Yammy</a>";
$pattern = '/<a[^>]*?href=(?:\'\'|"")[^>]*?>(.*?)<\/a>/i';
$replacement = '$1';
echo preg_replace($pattern, $replacement, $str);
Тестовое регулярное выражение: здесь
Это <a\h+href=(['"])\1>([^<>]*)<\/a>
регулярного выражение будет соответствовать всем якорям тегов, которые имеют пустое href
значения. Замена соответствует <a>
теги с $2
даст вам желаемый результат.
<?php
$str = "this is a bet and he is <a href=''>Mansoon</a> and he please search on <a href='http://www.google.com'>Google</a> and say he <a href=''>Yammy</a>";
echo preg_replace('~<a\h+href=([\'"])\1>([^<>]*)<\/a>~', '$2', $str);
?>
Вывод:
this is a bet and he is Mansoon and he please search on <a href='http://www.google.com'>Google</a> and say he Yammy
\h+
соответствует одному или нескольким горизонтальным символам пробела.
href
?
Это регулярное выражение будет работать для вас
<a[^>]*herf='*'[^>]*>[^>](.*?)<\/a> //works well even after space anywhere
herf
илиhref
?