Mokus
Mokus

Reputation: 10400

php string formation

I have a very simple question, for me not to simple, because I'm a student, but somewhere I have to start, so the question is I have a string array

array("+9%","+12%","+1%")

How could I format the output string, for example in the browser I want like this:

+ 9 %
+12 %
+ 1 %

Thans for your help.

Upvotes: 1

Views: 146

Answers (7)

Decent Dabbler
Decent Dabbler

Reputation: 22783

A bit over the top ;-) :

$array = array(
    '+196%',
    '+ 12%',
    '- 16 pct',
    '-84 %'
);

$rows = array();
foreach( $array as $element )
{
    preg_match( '/(?<sign>[-+])?\s?(?<number>[0-9]+)?\s?(?<remaining>.*)/', $element, $matches );
    $rows[] = '<div><span class="sign">' . $matches[ 'sign' ] . '</span><span class="number">' . $matches[ 'number' ] . '</span><span class="remaining">' . $matches[ 'remaining' ] . '</span></div>';
}

echo '
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8">
<title>Rows of data</title>
<style type="text/css">
span {
    float: left;
}
.sign {
    clear: left;
    width: 1ex;
}
.number {
    width: 4ex;
    padding-right: 1ex;
    text-align: right;
}
</style>
</head>
<body>
' . implode( PHP_EOL, $rows ) .  '
</body>
</html>';

Upvotes: 0

meze
meze

Reputation: 15087

As a solution that works with negative numbers and zero's and also is more compact:

$arr = array("+9%","+12%","+1%");
foreach($arr as $num) {
    echo preg_replace("~^([+-]?)(\d+)%$~e", "sprintf('%1s%2s %%', '$1', $2)",  $num)."<br/>";
}

Upvotes: 0

jonwayne
jonwayne

Reputation: 483

Sometimes answering these require noted caveats, so here are mine.

[1] I'm assuming all the values in the array would be percentages, so I dropped that out of my starting array, and appended them when I printed the string.

[2] I'm allowing for a positive or negative sign at the beginning of each element.

[3] I'm expecting the number value to be a whole number (I'm assuming you want the alignment as you had in your question, where each value takes up two spaces)

If any of these assumptions are incorrect, the code below would need to be modified to account for the changes.

<?php

$arrPercentages = array('+9','+12','+1');

foreach($arrPercentages as $strPercentage) {

    // Get rid of any spaces
    $strPercentage = str_replace(' ', '', $strPercentage);

    // Parse out the number
    preg_match('/([\-\+]{1})([0-9]+)/', $strPercentage, $arrMatches);

    // Don't continue if we didn't get a sign and number out of the string
    if(count($arrMatches)) {

        // Assign the "sign" to a variable
        $strSign = $arrMatches[1];

        // The number we want to print out as two character spaces
        $strNumber = $arrMatches[2];

        // Print it out!
        echo $strSign.sprintf("%2s", $strNumber).'%<br>';

    }

}

?>

Upvotes: 0

powtac
powtac

Reputation: 41040

My two cents:

foreach ($data as $entry) {  
    echo '+'.str_pad(trim(str_replace(array('+', '%'), $entry)), 2).' %';
}

Upvotes: 0

JohnP
JohnP

Reputation: 50009

Assuming the spaces in the output are a typo

You can use a foreach() loop to iterate through the aray

$myArray = array("+9%","+12%","+1%");
foreach ($myArray  as $elem) { 
   echo $elem . '<br>'; //BR is for breaks in the browser.
}

If the spaces aren't a typo, it gets a bit more tricky

$myArray = array("+9%","+12%","+1%");
foreach ($myArray  as $elem) { 
   $sign    = $elem[0]; //gets the first element of the string treated as an array
   $number  = substr($elem, 1, strpos($elem, '%') - 1); //gets the number part by starting from the left and going till you hit a % sign
   $percent = $elem[strlen($elem) - 1]; //getting the last part of the string
   echo "{$sign} {$number} {$percent} <br>";
}

The above code is pretty arbitrary and works ONLY for your array, but I've seen weirder homework assignments.

Upvotes: 1

algorithme
algorithme

Reputation: 113

Have a look at this page :

http://ch2.php.net/manual/fr/function.sprintf.php

It should be something like :

$values = array("+9%","+12%","+1%");
echo sprintf ("+%2d \n+%2d \n+2%d", intval($values[0]), intval($values[1]), intval($values[2])); 

Upvotes: 2

Uku Loskit
Uku Loskit

Reputation: 42040

<?
 foreach($yourarray as $element) {
    echo $element."<br />";
}


?>

Upvotes: 0

Related Questions