给定一个以逗号分隔的字符串,我们必须将其拆分为一个数组。
示例
Input: "Google,Bing,Yahoo!,DuckDuckGo" Output: arrar of strings after splitting... Array ( [0] => Google [1] => Bing [2] => Yahoo! [3] => DuckDuckGo )
<?php 即可反转字符串 //使用库函数 //函数定义 //它接受一个字符串并返回一个数组 //以逗号分隔 function split_string($text){ //变量以存储结果,即数组 $arr = []; //计算字符串长度 $strLength = strlen($text); $dl = ','; //厚度 $j = 0; $tmp = ''; //临时变量 //逻辑-它将检查所有字符 //并在找到逗号后分割字符串 for ($i = 0; $i < $strLength; $i++) { if($dl === $text[$i]) { $j++; $tmp = ''; continue; } $tmp .= $text[$i]; $arr[$j] = $tmp; } //返回结果 return $arr; } //主代码,即函数调用 $str = "New Delhi,Mumbai,Chennai,Banglore"; $result = split_string($str); echo "string is: " .$str. "<br/>"; echo "arrar of strings after splitting..."."<br/>"; print_r($result); $str = "Google,Bing,Yahoo!,DuckDuckGo"; $result = split_string($str); echo "string is: " .$str. "<br/>"; echo "arrar of strings after splitting..."."<br/>"; print_r($result); ?>
输出结果
string is: New Delhi,Mumbai,Chennai,Banglore arrar of strings after splitting... Array ( [0] => New Delhi [1] => Mumbai [2] => Chennai [3] => Banglore ) string is: Google,Bing,Yahoo!,DuckDuckGo arrar of strings after splitting... Array ( [0] => Google [1] => Bing [2] => Yahoo! [3] => DuckDuckGo )
说明:
我们使用for循环将逗号分隔的字符串转换为数组。我们确定字符串中何时出现(,),然后将其复制到数组中,然后执行此过程,直到覆盖整个字符串。倒置的字符串存储到临时变量($tmp)中,然后移到数组($arr [])中。