PHP implements a method of dividing a string by a specified distance _php tips

Source: Internet
Author: User
Tags strlen

The example in this article describes the method by which the PHP implementation splits a string at a specified distance. Share to everyone for your reference. Specifically as follows:

Adding a comma to every three characters of a string, such as converting the string 1234567890 to 1,234,567,890, is a common practice in the financial world

<?php
/**
 * Every 3 characters, separated by commas
 * @param string $str
 * @return string/
function Splitstrwithcomma ($str)
{
  $arr = array ();
  $len = strlen ($STR);
  for ($i = $len-1; $i >= 0;) {
    $new _str = "";
    for ($j = $i; $j > $i-3 && $j >= 0; $j-) {
      $new _str. = $str [$j];
    }
    $arr [] = $new _str;
    $i = $j;
  }
  $string = Implode (', ', $arr);
  Flip the string yourself to implement
  //$string = Strrev ($string);
  for ($i = 0, $j = strlen ($string)-1; $i <= $j; $i + +, $j-) {
    $tmp = $string [$i];
    $string [$i] = $string [$j];
    $string [$j] = $tmp;
  }
  return $string;
}
$str = "1234567890";
$new _str = Splitstrwithcomma ($STR);
Echo $new _str. "\ n";

I hope this article will help you with your PHP program design.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.