1

In my code I get a string which have html tags like so:

$string = '<div style="width:100px;">ABC 1234 <span> Test string, testing this string</span></div>';

Now, I removed the style attribute from the said string using preg_replace:

$string = preg_replace('/(<[^>]+) style=".*?"/i', '', $string);

After removing the style tag, I managed to remove the style attribute so the div tag ended up looking like <div>. The problem, I encountered after doing this is that I now get an excess > after the closing tag for the span so the string looks like this now:

$string = '<div>ABC 1234 <span> Test string, testing this string</span>   >     </div>';

My question is, why did I suddenly get an exccess >? Is there a different regular expression I can use that will get rid of the style attribute without the additional > appearing? Or is there any way I can get ride of this?

I tried using str_replace twice like so:

$string = str_replace("\n", "", $string);
$string = str_replace(">>", ">", $string);

But that did not work either.

I am not trying to remove the HTML tags, just the style part.

user1597438
  • 2,171
  • 5
  • 35
  • 78
  • 1
    [Avoid processing HTML with regex](http://stackoverflow.com/a/3577662/19068) – Quentin Oct 07 '13 at 09:17
  • 1
    your string is wrong you should use something like this `$string='
    ABC 1234 Test string, testing this string
    '`
    – Sina R. Oct 07 '13 at 09:17
  • 1
    What is your full replace code? not just the regular expression. – MDEV Oct 07 '13 at 09:22
  • Can't reproduce your result string. I get `
    ABC 1234 Test string, testing this string
    ` as result of the replace only.
    – Jerry Oct 07 '13 at 09:33
  • I think I was getting the said ">" because there were more html tags on my string. In any case, using addslashes before the preg_replace instead of the other way around seems to have done the trick. Thanks for all the assistance. – user1597438 Oct 09 '13 at 01:10

2 Answers2

0

I used This

$string = '<div style="width:100px;">ABC 1234 <span> Test string, testing this string</span></div>';
$output = preg_replace('/(<[^>]+) style=".*?"/i', '$1', $string);
die(htmlentities($output))

and the output is

<div>ABC 1234 <span> Test string, testing this string</span></div>

as you need

Osama Jetawe
  • 2,697
  • 6
  • 24
  • 40
0

Use it only for this string.

<?php
$string = "<div style=\"width:100px;\">ABC 1234 <span> Test string, testing this string</span></div>";

$string = strip_tags($string,"<span>");

$string = "<div>".$string."</div>";
?>

Now the string is:

<div>ABC 1234 <span> Test string, testing this string</span></div>
MD SHAHIDUL ISLAM
  • 14,325
  • 6
  • 82
  • 89