I have a string that looks like this:
<?php $string = "1000 - 2000"; ?>
I know if it were a single number I could format it like this:
<?php
$val = 1000;
echo sprintf("£%u", $val);
?>
Which would output "£1000" but I am unsure how to handle the two numbers separated by a hyphen. The needed result would be "£1000 – £2000"
3
Answers
You can create an array of values by splitting the string variable with hyphens as the delimiter, then for each value in the array format it, then as an example I added the formatted price to the array of formatted prices.
Above answer is Correct. But I would prefer not to use
sprintf()
. Instead I’ll simply concatenate the currency identifier.This will give you the desired output "£1000 – £2000"
First of all you have to look whether you can get the two numbers separately from wherever you’re getting them. That would be the preferred solution. However if this is impossible you can extract them from the string, and use them to create your new string.
I would use sscanf() in this case:
See live demo: https://3v4l.org/Va3Un