Benn
Benn

Reputation: 5023

How to wrap only words in spans php?

I have a text string mixed with html and need to separate words only and wrap them in spans.

String:

$string ='<div class="something">What </div> if it it is is same <div style="color:red;">same </div>';

desired output

<div class="something">
  <span class="splits split1">
    What
  </span>
</div>
<span class="splits split2">
  if
</span>
<span class="splits split3">
  it
</span>
<span class="splits split4">
  it
</span>
<span class="splits split5">
  is
</span>
<span class="splits split6">
  is
</span>
<span class="splits split7">
  same
</span>
<div style="color:red;">
  <span class="splits split8">
    same
  </span>
</div>

I tried everything I could think of, preg_replace with word boundary, preg_match , str_replace, combos with explodes , loops and replace, but one way or another the output fails and brakes the html or it adds replacement where it should not be.

Any help is appreciated.

Upvotes: 0

Views: 322

Answers (1)

revo
revo

Reputation: 48711

As @MarcB said, here with DOM life is tastier but since question is tagged this could be a workaround (not %100 guaranteed though):

</?\b[^<>]+>(*SKIP)(*F)|\w+

PHP:

preg_replace_callback('~</?\b[^<>]+>(*SKIP)(*F)|\w+~', function($matches) {
    static $counter = 0;
    return "<span class=\"splits split".(++$counter)."\">{$matches[0]}</span>";
}, $string);

Live demo

Upvotes: 1

Related Questions