This question is different to Split, a string, at every nth position, with PHP, in that I want to split a string like the following:
foo|foo|foo|foo|foo|foo
Into this (every 2nd |):
array (3) {
0 => 'foo|foo',
1 => 'foo|foo',
2 => 'foo|foo'
}
So, basically, I want a function similar to explode() (I really doubt that what I'm asking will be built-in), but which 'explodes' at every nth appearance of a certain string.
How is this possible?
You can use explode + array_chunk + array_map + implode
$string = "foo|foo|foo|foo|foo|foo";
$array = stringSplit($string,"|",2);
var_dump($array);
Output
array
0 => string 'foo|foo' (length=7)
1 => string 'foo|foo' (length=7)
2 => string 'foo|foo' (length=7)
Function used
function stringSplit($string, $search, $chunck) {
return array_map(function($var)use($search){return implode($search, $var); },array_chunk(explode($search, $string),$chunck));
}
Related
I have a string:
01;Tommy;32;Coder&&02;Annie;20;Seller
I want it like this:
array (size=2)
0 =>
array (size=4)
0 => string '01' (length=2)
1 => string 'Tommy' (length=5)
2 => int 42
3 => string 'Coder' (length=5)
1 =>
array (size=4)
0 => string '02' (length=2)
1 => string 'Annie' (length=5)
2 => int 20
3 => string 'Seller' (length=6)
Hope you can help me, thank you!
Not sure if the datatypes will be matching (as I believe it's all in a string) but here's the code
$myarray = array();
foreach(explode("&&",$mystring) as $key=>$val)
{
$myarray[] = explode(";",$val);
}
The explode command takes a string and turns it into an array based on a certain 'split key' which is && in your case
but since this is a dual array, I had to pass it through a foreach and another explode to solve.
It's very simple. First you need to explode the string by && and then traverse through array exploded by &&. And explode each element of an array by ;.
Like this,
<?php
$str="01;Tommy;32;Coder&&02;Annie;20;Seller";
$array=explode("&&",$str);
foreach($array as $key=>$val){
$array[$key]=explode(";",$val);
}
print_r($array);
Demo: https://eval.in/629507
you should just have to split on '&&', then split the results by ';' to create your new two dimensional array:
// $string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
// declare output
$output = [];
// create array of item strings
$itemarray = explode('&&',$string);
// loop through item strings
foreach($itemarray as $itemstring) {
// create array of item values
$subarray = explode(';',$itemstring);
// cast age to int
$subarray[2] = (int) $subarray[2]; // only useful for validation
// push subarray onto output array
$output[] = $subarray;
}
// $output = [['01','Tommy',32,'Coder'],['02','Annie',20,'Seller']];
keep in mind that since php variables are not typed, casting of strings to ints or keeping ints as strings will only last depending on how the values are used, however variable type casting can help validate data and keep the wrong kind of values out of your objects.
good luck!
There is another appropach of solving this problem. Here I used array_map() with anonymous function:
$string = '01;Tommy;32;Coder&&02;Annie;20;Seller';
$result = array_map(function($value){return explode(';',$value);}, explode('&&', $string));
I want to search for '01.' that begins with the number of the array.
Expected output:
1 => string '01.02' (length=5)
2 => string '01.03' (length=5)
3 => string '01.04' (length=5)
32 => string '02.02' (length=5)
33 => string '02.03' (length=5)
34 => string '02.04' (length=5)
35 => string '02.05' (length=5)
My code:
$key = array_search('/^01./', $tomb_datum);
echo $key;
var_dump($key);
These preg match not work.
There is a function dedicated for just this purpose, preg_grep. It will take a regular expression as first parameter, and an array as the second.
See the below example: FIDDLE
$haystack = array (
'01.02',
'01.03',
'02.05',
'02.07'
);
$matches = preg_grep ('/^01/i', $haystack);
print_r ($matches);
If you're looking to filter the array, use array_filter:
$resultArray = array_filter($array, function($elm) {
if (preg_match('/^01/', $elm)) {
return true;
}
return false;
});
Hope this helps.
You could use T-Regx library which allows for all sorts of array filters:
pattern('^01.')->forArray($tomb_datum)->filter()
You can also use other methods like:
filter() - for regular (sequential) arrays
filterAssoc() - for associative arrays (filterAssoc() preserves keys)
filterByKeys() - to filter an array by keys, not values
PS: Notice that with T-Regx you don't need /.?/ delimiters!
I have this array
array (size=7)
0 => string 'Â bs-0468R(20UG)' (length=16)
1 => string 'Â bs-1338R(1ML)' (length=15)
2 => string 'Â bs-1557G(NO BSA)' (length=18)
3 => string 'Â bs-3295R(NO BSA)' (length=18)
4 => string '" bs-0730R' (length=10)
5 => string '" bs-3889R' (length=10)
6 => string 'bs-0919R (NO BSA)' (length=17)
I want to throw away everything and only keep the string that start with bs.
What is the best of doing it ?
Something like this:
$result = array_filter($array, function ($i) {
return strpos($i, 'bs')===0;
});
I love preg_grep:
$result = preg_grep('/^bs/', $array);
I agree with #Casimir et Hippolyte. If you know you're always going to have a controlled dataset such as your example (rare), you can always just reference the string as an array -- which it already is under the hood:
$result = array_filter($array, function ($v) {
return $v[0] . $v[1] == 'bs';
});
Regex is amazing and not a performance problem for most situations, however I have had some issues with it where other functionalities were far faster and efficient when it counted. I understand that statement is not true for the majority of applications, but it is worth noting.
I have a string with many caracters and I need obtain data from it.
First of all, I did explode by ';', now I have an array and of each row I have a word into quotes.
I want to remove all, less this word into quotes. I know that is more easy to obtain these words with preg_match, but how is into an array, to save up to go over the array again, I would like to clean it directly with preg_replace.
$array = explode(';', $string);
//36 => string 's:7:"trans_1"' (length=13)
//37 => string 's:3:"104"' (length=9)
//38 => string 's:5:"addup"' (length=11)
//39 => string 's:1:"0"' (length=7)
$array = preg_replace('! !i', '', $array);
I would like to obtain:
//36 => string 'trans_1' (length=6)
//37 => string '104' (length=3)
//38 => string 'addup' (length=5)
//39 => string '0' (length=1)
I tryed differents things, but I can't rid off the letters outside the quotes.
While this isn't a direct answer to your question it solves your problem. The data you are looking at came from the php function serialize() to retrieve the data from that string you need to use the php function unserialize().
$data = unserialize($string);
You could try
preg_replace('!.*"([^"]*)".*!i', '\1', $array);
\1 refers to the first captured group!
I have an array $arr that when I var_dump looks like this. What's the easiest way to get the 2nd last item ('simple' in this case). I can't do $arr[4] because the number of items may vary per url, and I always want just the 2nd last. (note that there's an extra empty string at the end, which will always be there.)
array
0 => string 'http:' (length=5)
1 => string '' (length=0)
2 => string 'site.com'
3 => string 'group'
4 => string 'simple'
5 => string 'some-test-url'
6 => string '' (length=0)
So long as it is not a keyed or hashed array and it has more than two items...
$arr[count($arr) - 2];
Note: that my interpretation of second to last is second from the end. This may differ from yours. If so, subtract 3.
Get the count and subtract 3?
$arr[count($arr)-3]
if (!empty($arr) && count($arr)>1){
//or > 2, -3 for your extra ending
$val = $arr[count($arr)-2];
}
Should help you.
$second_last = count($array) - 3;
$value = $array[$second_last];
$arrayLen=count($arr);
echo $arr[$arrayLen-2];
Yet another alternative:
echo current(array_slice($data, -3, 1));