Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP: How to convert single quote to double quote in all HTML tags?

Tags:

string

php

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>
like image 872
marknt15 Avatar asked May 28 '09 07:05

marknt15


2 Answers

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.

like image 151
Xiaofu Avatar answered Oct 24 '22 18:10

Xiaofu


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/

like image 42
Keith Bentrup Avatar answered Oct 24 '22 19:10

Keith Bentrup