This article mainly introduces the method of dividing strings according to specified distances in PHP. It involves the skills of string operation and is of great practical value. Friends in need can refer to it.
The examples in this article are described PHP implements a method to split a string according to a specified distance. The details are as follows:
Add a comma to every three characters of 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";
Summary : The above is the entire content of this article, I hope it will be helpful to everyone's study.
Related recommendations:
A brief introduction to the decorator pattern in PHP design patterns
A brief introduction to the use of five types of PHP reflection
Definition and use of magic methods in PHP
The above is the detailed content of How to implement string splitting in php. For more information, please follow other related articles on the PHP Chinese website!