Kevin
Kevin

Reputation: 365

preg_replace between > and <

I have this:

<div> 16</div>

and I want this:

<div><span>16</span></div>

Currently, this is the only way I can make it work:

preg_replace("/(\D)(16)(\D)/", "$1<span>$2</span>$3", "<div> 16</div>")

If I leave off the $3, I get:

<div><span>16</span>/div>

Upvotes: 0

Views: 1044

Answers (4)

Kevin
Kevin

Reputation: 365

This is what ended up working the best:

preg_replace('/(<.*>)\s*('. $page . ')\s*(<.*>)/i', "$1" . '<span class="curPage">' . "$2" . '</span>' . "$3", $pagination)

What I found was that I didn't know for sure what tags would precede or follow the page number.

Upvotes: 0

Musa
Musa

Reputation: 4014

Try following -

$str = "<div class=\"number\"> 16</div>";
$formatted_str = preg_replace("/(<div\b[^>]*>)(.*?)<\/div>/i", "$1<span>$2</span></div>", $s);
echo $formatted_str;

Upvotes: 1

Robin Orheden
Robin Orheden

Reputation: 2764

Not quite sure what your after, but the following is more generic:

$value = "<div>    16    </div>";
echo(preg_replace('%(<(\D+)[^>]*>)\s*([^\s]*)\s*(</\2>)%', '\1<span>\3</span>\4', $value));

Which would result in:

<div><span>16</span></div>

Even if the value were:

<p>    16    </div>

It would result in:

<p><span>16</span></p>

Upvotes: 3

moinudin
moinudin

Reputation: 138357

I think you meant to say you're using the following:

print preg_replace("/(\\D+)(16)(\\D+)/", "$1<span>$2</span>$3", "<div>16</div>");

There's nothing wrong with that. $3 is going to contain everything matched in the second (\D+) group. If you leave it off, obviously it's not going to magically appear.

Note that your code in the question had some errors:

  1. You need to escape your \'s in a string.
  2. You need to use \D+ to match multiple characters.
  3. You have a space before 16 in your string, but you're not taking this into account in your regex. I removed the space, but if you want to allow for it you should use \s* to match any number of whitespace characters.
  4. The order of your parameters was incorrect.

Upvotes: 2

Related Questions