Forming data in php

What I need to do is format the data in a variable, for example:

format: xxx-xxx variable: 123456 output: 123-456

      

The problem is I need to change the format, so a static solution won't work. I also like to change the size of the variable, for example:

format: xxx-xxx variable: 1234 output: 1-234

      

Any ideas are appreciated! Thanks for your help!

Note. All variables will be numbers

Edit I had to clearly define a format that won't always group from 3, and may have more "-" as a symbol, the groups will be unstable 1-22 -333-4444 it will only be grouped 1-5

0


a source to share


3 answers


The best is preg_replace .

Regular expressions are addictive, but they are probably the best choice ...

EDIT:



//initial parsing
$val = preg_replace(
    '/(\d*?)(\d{1,2}?)(\d{1,3}?)(\d{1,4})$/', 
    '${1}-${2}-$[3}-${4}', 
    $inputString
);

//nuke leading dashes
$val - preg_replace('^\-+', '', $val);

      

The key is to make every set, except for the least greedy one, given a matching right-oriented pattern.

+1


a source


You can implement the strategic pattern and have new formatting classes that can be replaced at runtime. It looks complicated if you haven't seen it before, but it really helps with maintainability and allows you to switch the formatter at any time with setFormatter ().

class StyleOne_Formatter implements Formatter
{
    public function format($text)
    {
      return substr($text,0,3).'-'.substr($text,3);
    }
}

class StyleTwo_Formatter implements Formatter
{
    public function format($text)
    {
      return substr($text,0,1).'-'.substr($text,1);
    }
}

      

Then you will have your own formatting class, which will be like this:



class NumberFormatter implements Formatter
{

   protected $_formatter = null;

   public function setFormatter(Formatter $formatter)
   {
      $this->_formatter = $formatter;
   }

   public function format($text)
   {
     return $this->_formatter->format($text);
   }
}

      

Then you can use it like this:

 $text = "12345678910";
 $formatter = new NumberFormatter();

 $formatter->setFormatter(new StyleOne_Formatter());
 print $formatter->format($text);
 // Outputs 123-45678910

 $formatter->setFormatter(new StyleTwo_Formatter());
 print $formatter->format($text);
 // Outputs 1-2345678910

      

0


a source


If the input you are formatting is always an integer, you can try number_format and format as money (thousands, etc.). Here is a solution that takes any string and turns it into the format you want:

$split_position = 3;
$my_string      = '';
echo strrev(implode('-',(str_split(strrev($my_string),$split_position))));

input: 1234;     output: 1-234
input: abcdefab; output: ab-cde-fab
input: 1234567   output: 1-234-567

      

0


a source







All Articles