Example:
<div>foo</div>
<p>bar</p>
Unwrapped text
What i want:
<div>foo</div>
<p>bar</p>
<span>Unwrapped text</span>
How to achieve this without relying on new lines?
Example:
<div>foo</div>
<p>bar</p>
Unwrapped text
What i want:
<div>foo</div>
<p>bar</p>
<span>Unwrapped text</span>
How to achieve this without relying on new lines?
I would not use regular expressions for html.
You can do it with phpQuery
$doc = phpQuery::newDocument($html);
$doc->contents()->not($doc->children())->wrap("<span>");
$html = $doc->html();
Didn't try it though.
Extract tokens from your string like for example: <div>
, foo
, </div>
, <p>
, bar
, </p>
, Unwrapped text
. You can do this with regular expressions. Then
for each token do
if token is opening tag
push token on stack
else if token is closing tag (and matching opening tag is ontop of stack)
pop token from stack
else if token is text and stack is not empty
ignore token (continue)
else if token is text and stack is empty
wrap token with <span>
This will work for arbitrary nested XML
-strings.
Text
More text