0

I have a HTML string containing regular HTML with ID:s and classes in the following way:

<div id="my_id"></div>

I want to use a preg_replace in PHP to minify the strings in this way:

<div id=my_id></div>

In other words I want to remove the wrapping quote characters. How do I do this?

Viktor Svensson
  • 755
  • 3
  • 17
  • What did you try, what went wrong? At least show some effort :) (anyway, why would you want that? removing those 2 `"` will hardly be noticable in filesize?) – Nanne Dec 13 '13 at 10:52
  • 3
    You're playing with fire. better to leave that quotes. – Narek Dec 13 '13 at 10:54
  • I'm not very comfortable writing regexps to be honest, so I tried making some really ugly code looping through the string and removing quote marks. – Viktor Svensson Dec 13 '13 at 10:54
  • It's not noticable for a single user, but when you've gotten a million page loads it will be noticable. :) – Viktor Svensson Dec 13 '13 at 10:55
  • 1
    But it will be invalid HTML. – putvande Dec 13 '13 at 10:57
  • 3
    I honestly can't think of a valid reason why you'd want to do this. – Ben Fortune Dec 13 '13 at 10:58
  • You cannot have a regex transformation of an html document. It is mathematically not possible. You may only find solutions that will work on some cases, but never all of them. See http://stackoverflow.com/questions/1732348/regex-match-open-tags-except-xhtml-self-contained-tags – Pierre Arlaud Dec 13 '13 at 11:04

2 Answers2

1

Well, if quotes really matter, then try this:

$str = '<div id="my_id">say "good"</div><div id=\'sdafsdaf\'>la\'la</div>';

$str = preg_replace('/(<[^>]+\sid=)([\'"])([^\'"]+)\2/', '$1$3', $str);

// <div id=my_id>say "good"</div><div id=sdafsdaf>la'la</div>
var_dump($str);

But I do think save these "quotes" will just bring few benefits, 3% maybe, but compression methods, like gzip, might save 70% normally.

Andrew
  • 5,290
  • 1
  • 19
  • 22
  • Thanks! Yes, but we need those 3 %. The document is, of course, gzipped to. Everything is stripped down to save every single bit of bandwidth (loads of users). – Viktor Svensson Dec 13 '13 at 15:40
0

Try this:

preg_replace('/"/', '', $matches)
LightningBoltϟ
  • 1,383
  • 2
  • 10
  • 28