-3

How I can make all the numbers in a string bold?

For example: $st_nu = "Today123" would become Today<b>123</b>.

Laurel
  • 5,965
  • 14
  • 31
  • 57
Ronnie
  • 23
  • 1
  • 1
  • 7

2 Answers2

4

You can use a regular expression to bolden only numbers.

preg_replace('/(\d+)/', '<b>$1</b>', $st_nu);

What this does is matches any number 1 or more characters long, then surrounds it with the <b> tag (bold).

Using your example, you'd get back the following:

Today123

Chris Forrence
  • 10,042
  • 11
  • 48
  • 64
1

See this answer to remove the numbers from the string. Then, if you want to output it to HTML, you can wrap it in a <b> tag, or preferably use CSS to style it.

So you can do

preg_match_all('!\d+!', $st_nu, $matches);

Edit: I misunderstood your question a little. Here's a way to do it. If you have more than one number, you can loop through the matches array.

foreach ($matches as $res) {
    $replaceStr = "<b>" . $res . "</b>";
    str_replace($res, $replaceStr, $st_nu);
}
Community
  • 1
  • 1
Erik Godard
  • 5,930
  • 6
  • 30
  • 33
  • But I have a string like $srctitle = "Environment and Pollution , Volume 1, Issue 1, pages 536-555"; so it should display the numbers in that string in bold, using your example its showing array. – Ronnie Aug 15 '13 at 02:06