Home  >  Article  >  Backend Development  >  PHP method to split a string according to a specified distance_PHP tutorial

PHP method to split a string according to a specified distance_PHP tutorial

WBOY
WBOYOriginal
2016-07-13 10:03:10864browse

php implements the method of splitting strings according to the specified distance

This article describes the example of php implementing the method of dividing the string according to the specified distance. Share it with everyone for your reference. The details are as follows:

Add a comma every three characters to a string, for example, convert the string 1234567890 to 1,234,567,890. This practice is very common in the financial field

<?php
/**
 * 每隔3个字符,用逗号进行分隔
 * @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);
  // 翻转字符串自己实现
  // $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 be helpful to everyone’s PHP programming design.

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/969340.htmlTechArticleHow to use PHP to split a string according to a specified distance. This example describes how to use PHP to split a string according to a specified distance. method of segmentation. Share it with everyone for your reference. Specifically...
Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn