preg_replace how surround html attributes for a string with " in PHP

廉价感情. 提交于 2020-01-11 10:26:15

问题


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.



来源:https://stackoverflow.com/questions/13323723/preg-replace-how-surround-html-attributes-for-a-string-with-in-php

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!