Related
This question already has answers here:
How can I split a string on the third occurrence of something?
(4 answers)
Closed 8 months ago.
I have a string is below,
$string = "div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0, div-item-1,4,maintype:text| heading:Image| isactive:1,4,0, div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";"
Now I would like to convert this string as a sub-string to be an array element is as below,
$array = [
"div-item-0,4,maintype:menu| heading: Quick, Link| isactive:1,0,0",
"div-item-1,4,maintype:text| heading:Image| isactive:1,4,0",
"div-item-2,4,maintype:social| heading:Social| isactive:1,8,0",
];
After five commas counted in the $string, a substring will be converted as an array element.
How can I do it using PHP?
You could use the array_chunk method to solve this
<?php
$string = "
div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0,
div-item-1,4,maintype:text| heading:Image| isactive:1,4,0,
div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";
$temp = explode(',', $string); // just create one big array
$temp = array_chunk($temp, 5); // group the array per 5 parts
foreach($temp as &$value) $value = trim(implode(',', $value)); // recombine to one string
var_dump($temp);
demo
Based on the input string in the question, you can also use preg_split, splitting on a comma followed by a newline:
$array = preg_split('/,\s+/', trim($string));
print_r($array);
Output:
Array
(
[0] => div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0
[1] => div-item-1,4,maintype:text| heading:Image| isactive:1,4,0
[2] => div-item-2,4,maintype:social| heading:Social| isactive:1,8,0
)
Demo on 3v4l.org
Update
Based on the comments, I now understand there isn't intended to be any whitespace in the string. In this case, you can still use preg_split with a more complex regex, and using the flags PREG_SPLIT_DELIM_CAPTURE to capture the contents of the regex and PREG_SPLIT_NO_EMPTY to remove empty strings from the result:
$array = preg_split('/((?:[^,]+,){4}[^,]+),\s*/', trim($string), -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($array);
Output is the same. Demo on 3v4l.org
We can try using preg_match_all here with the following regex:
((?:[^,]*,){4}[^,]+)(?:,|$)
This will match a term having fives commas, but won't capture the final fifth comma as the first capture group.
$string = "
div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0,
div-item-1,4,maintype:text| heading:Image| isactive:1,4,0,
div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";
preg_match_all("/((?:[^,]*,){4}[^,]+)(?:,|$)/", $string, $matches);
print_r($matches[1]);
This prints:
Array
(
[0] => div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0
[1] => div-item-1,4,maintype:text| heading:Image| isactive:1,4,0
[2] => div-item-2,4,maintype:social| heading:Social| isactive:1,8,0
)
I'm not a PHP expert, but its just a split and reform in any language.
<?php
$string = "div-item-0,4,maintype:menu| heading: Quick Link|
isactive:1,0,0,div-item-1,4,maintype:text| heading:Image|
isactive:1,4,0,div-item-2,4,maintype:social| heading:Social|
isactive:1,8,0";
$items = explode("div-item",$string);
$target = array();
foreach( $items as $item){
if($item !== '')
array_push($target,"div-item".$item);
}
print_r($target); //Your array
?>
Will yield
Array
(
[0] => div-item-0,4,maintype:menu| heading: Quick Link|
isactive:1,0,0,
[1] => div-item-1,4,maintype:text| heading:Image|
isactive:1,4,0,
[2] => div-item-2,4,maintype:social| heading:Social|
isactive:1,8,0
)
I do not see any newlines in the shown string.
And is the number of commas always the same for the separation?
What is in the original: "heading: Quick, Link" or "heading: Quick Link"?
The expected array shows me that every array element should start with a "div". Why not use "div" or "div-item" to separate?
Under these conditions do also do that:
$string = "div-item-0,4,maintype:menu| heading: Quick Link| isactive:1,0,0, div-item-1,4,maintype:text| heading:Image| isactive:1,4,0, div-item-2,4,maintype:social| heading:Social| isactive:1,8,0";
$array = preg_split('~(?=div)~', $string,-1, PREG_SPLIT_NO_EMPTY);
This question already has answers here:
preg_split() String into Text and Numbers [duplicate]
(2 answers)
Closed 4 years ago.
Sorry for my bad English, I would to ask about How to split characters and numbers using preg_split(). For example, I have any data with prefix like :
ABC00001 to array(0 => 'ABC', 1 => 00001)
DEFG00002 to array(0 => 'DEFG', 1 => 00002)
AB00003 to array(0 => 'AB', 1 => 00003)
Thanks for advise
Split on the zero-length position that follows the sequence of letters.
Code: Demo
$string = 'ABC00001';
$output = preg_split('~[A-Z]+\K~', $string);
var_export($output);
The \K says forget the previous matched characters.
You can use preg_split with the PREG_SPLIT_DELIM_CAPTURE and PREG_SPLIT_NO_EMPTY flags to do what you want:
$string = 'ABC00001';
$output = preg_split('/([A-Z]+)/', $string, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
print_r($output);
Output:
Array ( [0] => ABC [1] => 00001 )
Demo on 3v4l.org
After instructing clients to input only
number comma number comma number
(no set length, but generally < 10), the results of their input have been, erm, unpredictable.
Given the following example input:
3,6 ,bannana,5,,*,
How could I most simply, and reliably end up with:
3,6,5
So far I am trying a combination:
$test= trim($test,","); //Remove any leading or trailing commas
$test= preg_replace('/\s+/', '', $test);; //Remove any whitespace
$test= preg_replace("/[^0-9]/", ",", $test); //Replace any non-number with a comma
But before I keep throwing things at it...is there an elegant way, probably from a regex boffin!
In a purely abstract sense this is what I'd do:
$test = array_filter(array_map('trim',explode(",",$test)),'is_numeric')
Example:
http://sandbox.onlinephpfunctions.com/code/753f4a833e8ff07cd9c7bd780708f7aafd20d01d
<?php
$str = '3,6 ,bannana,5,,*,';
$str = explode(',', $str);
$newArray = array_map(function($val){
return is_numeric(trim($val)) ? trim($val) : '';
}, $str);
print_r(array_filter($newArray)); // <-- this will give you array
echo implode(',',array_filter($newArray)); // <--- this give you string
?>
Here's an example using regex,
$string = '3,6 ,bannana,5,-6,*,';
preg_match_all('#(-?[0-9]+)#',$string,$matches);
print_r($matches);
will output
Array
(
[0] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
[1] => Array
(
[0] => 3
[1] => 6
[2] => 5
[3] => -6
)
)
Use $matches[0] and you should be on your way.
If you don't need negative numbers just remove the first bit in the in the regex rule.
$str="a,b,c,d-e,f,g,h"
I am trying to extract the strings from $str that are separated "," and are before "-" in one array and the strings separated by "," and are after "-" in second array. So that $arr1=array(a,b,c,d); and $arr2=array(e,f,g,h);. I am just using $str as an example and generally I want this to work for any string of the same form i.e. $str=s1,s2,s3,s4,s5,....-r1,r2,t3....
NOTE: If $str doesn't have "-" then $arr2 vanishes and $arr1 contains an array of the elements separated by ',' in $str.
This is what I tried
preg_match_all('~(^|.*,)(.*)(,.*|\-|$)~', $str, $arr1);
preg_match_all('~(-|.*,)(.*)(,.*|$)~', $str, $arr2);
However each array comes with one element that contains the string str.
Does anyone know why this is not working.
All of your regex patterns are not optimal and it seems the task is easier to solve with explode and array_map:
array_map() returns an array containing all the elements of array1 after applying the callback function to each one. The number of parameters that the callback function accepts should match the number of arrays passed to the array_map()
$str="a,b,c,d-e,f,g,h";
$ex = array_map(function ($s) {
return explode(",", $s);
}, explode("-", $str));
print_r($ex);
See IDEONE demo
Results:
Array
(
[0] => Array
(
[0] => a
[1] => b
[2] => c
[3] => d
)
[1] => Array
(
[0] => e
[1] => f
[2] => g
[3] => h
)
)
^(.*?(?=-|$))|(?<=-)(.*$)
You can use this to get 2 arrays.See demo.
https://regex101.com/r/vV1wW6/19
Your regex is not working as you have used greedy modifier..*, will stop at the last instance of ,
EDIT:
Use this is you want string after - to be in second group.
^(.*?(?=-|$))(?:-(.*$))?
https://regex101.com/r/vV1wW6/20
You can simply use preg_match to check does your string contains - if yes than can simply use array_walk like as
$str = 'a,b,c,d-e,f,g,h';
$result = [];
if(preg_match('/[-]/', $str)){
array_walk(explode('-',$str),function($v,$k)use(&$result){
$result[] = explode(',',$v);
});
}else{
array_walk(explode(',',$str),function($v,$k)use(&$result){
$result[] = $v;
});
}
print_r($result);
Without regex (the most reasonable way):
$str="a,b,c,d-e,f,g,h";
list($arr1, $arr2) = explode('-', $str);
$arr1 = explode(',', $arr1);
if ($arr2)
$arr2 = explode(',', $arr2);
else
unset($arr2);
With regex (for the challenge):
if (preg_match_all('~(?:(?!\G)|\A)([^-,]+)|-?([^,]+),?~', $str, $m)) {
$arr1 = array_filter($m[1]);
if (!$arr2 = array_filter($m[2]))
unset($arr2);
}
This question already has answers here:
Explode string by one or more spaces or tabs
(8 answers)
Closed 7 months ago.
With the following string:
$str = '["one","two"],a,["three","four"],a,,a,["five","six"]';
preg_split( delimiter pattern, $str );
How would I have to set up the delimiter pattern to obtain this result:
$arr[0] = '["one","two"]';
$arr[1] = '["three","four"]';
$arr[2] = '["five","six"]';
In other words, is there a way to split at the pattern ',a,' AND ',a,,a,' BUT check for ',a,,a,' first because ',a,' is a sub string of ',a,,a,'?
Thanks in advance!
If it can only be ,a, and ,a,,a,, then this should be enough:
preg_split("/(,a,)+/", $str);
It looks like what you're actually trying to do is separate out the square bracketed parts. You could do that like so:
$arr = preg_split("/(?<=\])[^[]*(?=\[)/",$str);
Take a look at this code:
$result = array();
preg_match_all("/(\[[^\]]*\])/", '["one","two"],a,["three","four"],a,,a,["five","six"]', $result);
echo '<pre>' . print_r($result, true);
It will return:
Array
(
[0] => Array
(
[0] => ["one","two"]
[1] => ["three","four"]
[2] => ["five","six"]
)
[1] => Array
(
[0] => ["one","two"]
[1] => ["three","four"]
[2] => ["five","six"]
)
)