skip to Main Content

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


  1. 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.

    $string = "1000 - 2000";
    $values = explode(' - ', $string);
    $prices = [];
    
    foreach ($values as $value) {
        $price = sprintf("£%u", $value);
        echo $price;
        $prices[] = $price;
    }
    
    Login or Signup to reply.
  2. Above answer is Correct. But I would prefer not to use sprintf(). Instead I’ll simply concatenate the currency identifier.

    $string = "1000 - 2000";
    $currencyIdentifier = "£";
    $values = explode(' - ', $string);
    $prices = [];
    
    foreach ($values as $value) {
        $price = $currencyIdentifier.$value;
        echo $price.'<br/>';
        $prices[] = $price;
    }
    print_r($prices);
    $newPrice = implode(' - ', $prices);
    echo '<br/>'.$newPrice;
    

    This will give you the desired output "£1000 – £2000"

    Login or Signup to reply.
  3. 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:

    $string = "1000 - 2000";
    sscanf($string, '%d - %d', $price1, $price2);
    echo "£$price1 - £$price2";
    

    See live demo: https://3v4l.org/Va3Un

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search