数据库拆分字符串函数_PHP | 不使用库函数将逗号分隔的字符串拆分为数组

古城微笑少年丶 2023-03-05 04:29 35阅读 0赞

数据库拆分字符串函数

Given a string with comma delimited, we have to split it into an array.

给定一个以逗号分隔的字符串,我们必须将其拆分为一个数组。

Example:

例:

  1. Input:
  2. "Google,Bing,Yahoo!,DuckDuckGo"
  3. Output:
  4. arrar of strings after splitting...
  5. Array
  6. (
  7. [0] => Google
  8. [1] => Bing
  9. [2] => Yahoo!
  10. [3] => DuckDuckGo
  11. )

PHP代码将逗号分隔的字符串拆分为数组,而无需使用库函数 (PHP code to split comma delimited string into an array without using library function)

  1. <?php
  2. //PHP code to reverse the string without
  3. //using library function
  4. //function definition
  5. //it accepts a string and returns an array
  6. //delimited by commas
  7. function split_string($text){
  8. //variable to store the result i.e. an array
  9. $arr = [];
  10. //calculate string length
  11. $strLength = strlen($text);
  12. $dl = ','; //delimeter
  13. $j = 0;
  14. $tmp = ''; //a temp variable
  15. //logic - it will check all characters
  16. //and split the string when comma found
  17. for ($i = 0; $i < $strLength; $i++) {
  18. if($dl === $text[$i]) {
  19. $j++;
  20. $tmp = '';
  21. continue;
  22. }
  23. $tmp .= $text[$i];
  24. $arr[$j] = $tmp;
  25. }
  26. //return the result
  27. return $arr;
  28. }
  29. //main code i.e. function calling
  30. $str = "New Delhi,Mumbai,Chennai,Banglore";
  31. $result = split_string($str);
  32. echo "string is: " .$str. "<br/>";
  33. echo "arrar of strings after splitting..."."<br/>";
  34. print_r($result);
  35. $str = "Google,Bing,Yahoo!,DuckDuckGo";
  36. $result = split_string($str);
  37. echo "string is: " .$str. "<br/>";
  38. echo "arrar of strings after splitting..."."<br/>";
  39. print_r($result);
  40. ?>

Output

输出量

  1. string is: New Delhi,Mumbai,Chennai,Banglore
  2. arrar of strings after splitting...
  3. Array
  4. (
  5. [0] => New Delhi
  6. [1] => Mumbai
  7. [2] => Chennai
  8. [3] => Banglore
  9. )
  10. string is: Google,Bing,Yahoo!,DuckDuckGo
  11. arrar of strings after splitting...
  12. Array
  13. (
  14. [0] => Google
  15. [1] => Bing
  16. [2] => Yahoo!
  17. [3] => DuckDuckGo
  18. )

Explanation:

说明:

We use a for loop to convert our comma delimited string into an array. We identify when a (,) appears in the string and copy that into an array then follow this process until the whole length of the string is covered. The inverted string is stored into a temporary variable ($tmp) then moved to an array ($arr[]).

我们使用for循环将逗号分隔的字符串转换为数组。 我们确定字符串中何时出现( , ),然后将其复制到数组中,然后执行此过程,直到覆盖整个字符串。 倒置的字符串存储到一个临时变量( $ tmp )中,然后移到一个数组( $ arr [] )中。

翻译自: https://www.includehelp.com/php/split-comma-delimited-string-into-an-array-without-using-library-function.aspx

数据库拆分字符串函数

发表评论

表情:
评论列表 (有 0 条评论,35人围观)

还没有评论,来说两句吧...

相关阅读