0

I have a srting like this.

$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>";

I want to remove all a href tags from string with blank href. Can you please loook into this.

Output like this

$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";

Many thanks

Davide Pastore
  • 8,678
  • 10
  • 39
  • 53
bhupendra
  • 43
  • 3
  • 10

4 Answers4

4

try this: Update it may full fill all exception cases :

$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);

live demo

Ahosan Karim Asik
  • 3,219
  • 1
  • 18
  • 27
0

This regular expression will works for you

<a[^>]*herf='*'[^>]*>[^>](.*?)<\/a> //works well even after space anywhere
Lalit Sharma
  • 555
  • 3
  • 12
0

This <a\h+href=(['"])\1>([^<>]*)<\/a> regex would match all the anchor tags which has an empty href value. Replacing the matched <a> tags with $2 will give you the desired output.

DEMO

<?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);
?>

Output:

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+ matches one or more horizontal whitespace characters.

Avinash Raj
  • 172,303
  • 28
  • 230
  • 274
0

You can use:

$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);

Test regex: here

Croises
  • 18,570
  • 4
  • 30
  • 47