0

I am trying to wrap numbers inside a given string in a <span>.

$datitle = "hey hey 13";

$datitle = preg_replace('/[0-9]/', '<span class="title-number">$1</span>', $datitle);

However that returns:

hey hey <span class="title-number"></span><span class="title-number"></span>

With two empty spans, without the number inside.

What I want to get is:

hey hey <span class="title-number">13</span>

How do I use the number matched by preg_replace as a backreference?

1 Answer 1

2

First of all /[0-9]/ means One number from 0 to 9. This means 1 fits your regexp, 3 fits your regexp. Not 13.

Second - items which are not wrapped in a () are not stored as a result of regexp. But full regexp is stored in $0.

So proper code is:

$datitle = "hey hey 13";
$datitle = preg_replace('/([0-9]+)/', '<span class="title-number">$1</span>', $datitle);
echo $datitle; // hey hey <span class="title-number">13</span>

Or:

$datitle = "hey hey 13";
$datitle = preg_replace('/[0-9]+/', '<span class="title-number">$0</span>', $datitle);
echo $datitle; // hey hey <span class="title-number">13</span>
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.