Parting string in PHP: Here, we will figure out how to part comma delimited string into a cluster without utilizing library function in PHP?
Given a string with comma-delimited, we need to part it into an exhibit.
Example:
Input:
"Google,Bing,Yahoo!,DuckDuckGo"
Output:
arrar of strings after splitting...
Array
(
[0] => Google
[1] => Bing
[2] => Yahoo!
[3] => DuckDuckGo
)
PHP code to part comma delimited string into an exhibit without utilizing library function:
<?php
//PHP code to reverse the string without
//using library function
//function definition
//it accepts a string and returns an array
//delimited by commas
function split_string($text){
//variable to store the result i.e. an array
$arr = [];
//calculate string length
$strLength = strlen($text);
$dl = ','; //delimeter
$j = 0;
$tmp = ''; //a temp variable
//logic - it will check all characters
//and split the string when comma found
for ($i = 0; $i < $strLength; $i++) {
if($dl === $text[$i]) {
$j++;
$tmp = '';
continue;
}
$tmp .= $text[$i];
$arr[$j] = $tmp;
}
//return the result
return $arr;
}
//main code i.e. function calling
$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);
?>
Output:
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
)
Clarification:
We utilize a for the circle to change over our comma delimited string into a cluster. We recognize when a (,) shows up in the string and duplicate that into an exhibit at that point follow this procedure until the entire length of the string is secured. The upset string is put away into an impermanent variable ($tmp) at that point moved to an exhibit ($arr[]).