preg_replace how surround html attributes for a st

2019-02-27 08:28发布

问题:

I have a string variable in PHP , its content is:

$var='<SPAN id=1 value=1 name=1> one</SPAN>
<div id=2 value=2 name=2> two</div >';
 ....

I need a function for surround html attributes with "" i need do this for the all meta-tag

,etc the result should be this:

$var='<SPAN id= "1" value="1" name="1"> one </SPAN>
<div id="2" value="2" name="2" > two</div >';
 ...

I need replace all =[a-z][A-Z][1-9] for ="[a-z][A-Z][1-9]". I need a regular expresion for preg_replace

回答1:

You need to wrap it all in single quotes like this:

$myHtml='<SPAN id="1" value="1" name="1"> one </SPAN>
    <div id="2" value="2" name="2" > two</div >';


回答2:

Its is the solution

$var = preg_replace('/(?<==)(\b\w+\b)(?!")(?=[^<]*>)/', '"$1"', $var);

thanks for Ωmega, its works on IE8



回答3:

use a heredoc which removes the need to escape most anything except $:

$var = <<<EOL
<span id="1" value="1" name="1">one</span>
etc...
EOL


回答4:

I would run the string through DOMDocument:

$var='<SPAN id=1 value=1 name=1> one</SPAN>
<div id=2 value=2 name=2> two</div >';

// Create a new DOMDocument and load your markup.
$dom = new DOMDocument();
$dom->loadHTML($var);

// DOMDocument adds doctype and <html> and <body> tags if they aren't
// present, so find the contents of the <body> tag (which should be
// your original markup) and dump them back to a string.
$var = $dom->saveHTML($dom->getElementsByTagName('body')->item(0));

// Strip the actual <body> tags DOMDocument appended.
$var = preg_replace('#^<body>\s*(.+?)\s*</body>$#ms', '$1', $var);

// Here $var will be your desired output:
var_dump($var);

Output:

string(85) "<span id="1" value="1" name="1"> one</span>\n<div id="2" value="2" name="2"> two</div>"

Please note that if $var has the potential to contain an actual <body> tag, that modifications will need to be made to this code. I leave that as an exercise to the OP.