我将通过以下方式运行字符串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);
输出:
string(85) "<span id="1" value="1" name="1"> one</span>\n<div id="2" value="2" name="2"> two</div>"
请注意,如果$var
有可能包含实际<body>
标签,则需要对此代码进行修改。我把它作为练习留给 OP。