-2

How can I take a string like this: *Up to* $1,000

and turn it into this: <span>Up to</span> $1,000

The stars can be anywhere in the string and also there can be multiple sets of stars. But each set should replaced with span's.

e.g.

text *test* here = text <span>test</span> here

text here *test* right *now* = text here <span>test</span> right <span>now</span>

I need to be able to pass the value into a function and receive the formatted string in return. Thanks ahead of time.

DarkBee
  • 16,592
  • 6
  • 46
  • 58
Bryce
  • 988
  • 9
  • 16
  • Thanks! I couldn't find that other question for the life of me! I looked for a good half hour before asking the question. – Bryce Aug 15 '17 at 15:47

1 Answers1

1

Simple regex can do this:

function replace_star($str) {
    return preg_replace('~\*([^*]*)\*~ms', '<span>\1</span>', $str);
}

echo replace_star('*Up to* $1,000') . "\n";
echo replace_star('text here *test* right *now*');

Output:

<span>Up to</span> $1,000
text here <span>test</span> right <span>now</span>
Scoots
  • 3,048
  • 2
  • 21
  • 33