Home  >  Article  >  Backend Development  >  php实现将字符串按照指定距离进行分割的方法_php技巧

php实现将字符串按照指定距离进行分割的方法_php技巧

WBOY
WBOYOriginal
2016-05-16 20:20:55951browse

本文实例讲述了php实现将字符串按照指定距离进行分割的方法。分享给大家供大家参考。具体如下:

将一个字符串每隔三个字符添加一个逗号,例如把字符串1234567890转换为1,234,567,890,这种做法在金融领域非常常见

<&#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";

希望本文所述对大家的php程序设计有所帮助。

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