How to split string and iterate in php
There are a few things wrong with your code
- All variables must start with a $
$meal = explode('-', $string, 2);
you use $string again instead of $item- With PHP you've to concatenation strings with a
.
not with a+
- At the end of each line you've to place a ;
If you fix al those problems you get something like:
<?php
$string = "city-3|country-4";
$str1 = explode('|', $string, );
foreach ($str1 as $item) {
$meal = explode('-', $item, 2);
if ($meal[0]=="city")
{
echo "city duration " . $meal[1];
}
else if ($meal[0]=="country")
{
echo "country duration " . $meal[1];
}
echo "<br />";
}
?>
PHP - Split String Into Arrays for every N characters
You could do something like this:
$text = 'VERY LONG STRING';
$result = [];
$partial = [];
$len = 0;
foreach(explode(' ', $text) as $chunk) {
$chunkLen = strlen($chunk);
if ($len + $chunkLen > 5000) {
$result[] = $partial;
$partial = [];
$len = 0;
}
$len += $chunkLen;
$partial[] = $chunk;
}
if ($partial) {
$result[] = $partial;
}
You can test it more easily if you do it with a lower max length
Split string into two
Yes, explode() and implode() are fast, reliable, and made for this sort of requirement.
Split string with only one delimiting character into key-value pairs
Try this
$string = "Part1:Part2:Part3:Part4";
$arr = explode(":", $string);
$key = "";
$i = 0;
$newArray = [];
foreach($arr as $row){
if($i == 0){
$key = $row;
$i++;
} else {
$newArray[$key] = $row;
$i = 0;
}
}
echo "<pre>";
print_r($newArray);
echo "</pre>";
Split String Into Array and Append Prev Value
This solution takes the approach of starting with your input path, and then removing a path one by one, adding the remaining input to an array at each step. Then, we reverse the array as a final step to generate the output you want.
$input = "var/log/file.log";
$array = [];
while (preg_match("/\//i", $input)) {
array_push($array, $input);
$input = preg_replace("/\/[^\/]+$/", "", $input);
echo $input;
}
array_push($array, $input);
$array = array_reverse($array);
print_r($array);
Array
(
[0] => var
[1] => var/log
[2] => var/log/file.log
)
The above call to preg_replace
strips off the final path of the input string, including the forward slash. This is repeated until there is only one final path component left. Then, we add that last component to the same array.
Split a string at comma character but ignore if said character is nested inside parentheses
You can use preg_split()
method for this (documentation). You can use this to split the string based on a regex pattern for comma separated values but ignored if these are between parentheses.
This code works for your example:
<?php
$string = 'v70, 790, v50 (v40, v44), v22';
$pattern = '/,(?![^(]*\)) /';
$splitString = preg_split($pattern, $string);
Output of $splitString
looks like:
array (size=4)
0 => string 'v70' (length=3)
1 => string '790' (length=3)
2 => string 'v50 (v40, v44)' (length=14)
3 => string 'v22' (length=3)
How to split a string at a specific character but not replace that character?
You can use Lookahead and Lookbehind Zero-Length Assertions.
Example:
// string
$str = "abc;def;ghi{jkl;}if('mno') {pqr;}";
// expression
$pattern = "/(?=[;{\(])/";
$result = preg_split($pattern, $str);
$result is a array like
array (
0 => "abc",
1 => ";def",
2 => ";ghi",
3 => "{jkl",
4 => ";}if",
5 => "('mno') ",
6 => "{pqr",
7 => ";}",
)
Split string into 2 letters
Here it is:
function SplitStringInWeirdWay($string, $num) {
for ($i = 0; $i < strlen($string)-$num+1; $i++) {
$result[] = substr($string, $i, $num);
}
return $result;
}
$string = "aeioubcdfghjkl";
$array = SplitStringInWeirdWay($string, 4);
echo "<pre>";
print_r($array);
echo "</pre>";
PHPFiddle Link: http://phpfiddle.org/main/code/1bvp-pyk9
And after that, you can just simply echo it in one line, like:
echo implode($array, ' ');
Related Topics
How to Add/Remove Pkcs7 Padding from an Aes Encrypted String
Method="Post" Enctype="Text/Plain" Are Not Compatible
How to Call a PHP Function on the Click of a Button
Deny Direct Access to a Folder and File by Htaccess
How to Check If Mod_Rewrite Is Enabled in PHP
"Cannot Send Session Cache Limiter - Headers Already Sent"
How to Get Protected Property of Object in PHP
Using PHP 5.5'S Password_Hash and Password_Verify Function
Correct Way to Use Like '%{$Var}%' With Prepared Statements
PHP: How to Get All Possible Combinations of 1D Array
Is There a PHP Function Like Python'S Zip
Truncate a Multibyte String to N Chars
What Is Thread Safe or Non-Thread Safe in PHP
What's the Use of Ob_Start() in PHP
How to Post Json to PHP With Curl
PHP Error: Fatal Error: Constant Expression Contains Invalid Operations