Home >Backend Development >PHP Tutorial >PHP implements a method to split a string according to a specified distance, PHP string_PHP tutorial

PHP implements a method to split a string according to a specified distance, PHP string_PHP tutorial

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

php implements the method of dividing strings according to the specified distance, php string

The example in this article describes the method of php 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

<&#63;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/967739.htmlTechArticlephp implements the method of dividing strings according to specified distances. php string This article describes how php implements dividing characters A method to split a string according to a specified distance. Share it with everyone for everyone...
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