How can I convert all single quotes to double quotes in all HTML tags only? Is there an easier way to do it? Thanks :)
For example: How can I convert this string (actual data from my work):
<TEXTFORMAT LEADING='2'><P ALIGN='LEFT'><FONT FACE='Verdana' style="font-size:10' COLOR='#0B333C'>My name's Mark</FONT></P></TEXTFORMAT>
To this:
<TEXTFORMAT LEADING="2"><P ALIGN="LEFT"><FONT FACE="Verdana" style="font-size:10" COLOR="#0B333C">My name's Mark</FONT></P></TEXTFORMAT>
If you don't care about the JavaScript and CSS issues mentioned elsewhere, try this:
$text = "<TEXTFORMAT LEADING='2'><P ALIGN='LEFT'><FONT FACE='Verdana' style='font-size:10' COLOR='#0B333C'>My name's Mark</FONT></P></TEXTFORMAT>";
echo preg_replace('/<([^<>]+)>/e', '"<" . str_replace("\\\\\'", \'"\', "$1") . ">"', $text);
This is taken from a thread by someone with exactly the same problem as you over at devshed.com.
I'm assuming that when you say in all html tags, that you mean all single quotes that contain an attribute. You wouldn't want <a onclick="alert('hi')">
converted b/c it would break the code.
Any regular expression is going to be fragile. If you know your input will be a particular set of simple cases, you might be ok with a regex. Otherwise, you'll want a DOM parser that understands complex html markup like onmouseover="(function () { document.getElementById(''); alert(\"...\")...})()"
(for example). Add to that an attribute can span multiple lines. ;)
I haven't had to tackle this particular problem recently, but maybe there's a good way to do it with HTML Tidy (more here: http://devzone.zend.com/article/761) or a parser like this one http://sourceforge.net/projects/simplehtmldom/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With