PHP array_search preg - php

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!

Related

Explode string with two different separators to create multidimensional array

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));

How to keep only string(s) that start with "bs"?

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.

Sorting Array by Key (Key is a string)

I have a simple Array. The goal is, to sort them ascending by the key.
$someUnsortedArray = array("140/142" => "FirstValue", "118/120" => "SecondValue", "122/124" => "ThirdValue", "40/42" => "FourthValue");
ksort($someUnsortedArray);
My Output:
array (size=4)
'118/120' => string 'SecondValue'
'122/124' => string 'ThirdValue'
'140/142' => string 'FirstValue'
'40/42' => string 'FourthValue'
Expected Output:
array (size=4)
'40/42' => string 'FourthValue'
'118/120' => string 'SecondValue'
'122/124' => string 'ThirdValue'
'140/142' => string 'FirstValue'
What's the function in php I am searching for?
You could use uksort() in this case:
$someUnsortedArray = array("140/142" => "FirstValue", "118/120" => "SecondValue", "122/124" => "ThirdValue", "40/42" => "FourthValue");
uksort($someUnsortedArray, function($a, $b){
$a = str_replace('/', '', $a);
$b = str_replace('/', '', $b);
return $a - $b;
});
echo '<pre>';
print_r($someUnsortedArray);
As an alternative, you can also make use of the natural order string compare function to compare the keys
function sortKey($a, $b) {
return strnatcmp($a, $b);
}
uksort($someUnsortedArray,"sortKey");
Checking php manual:
http://php.net/manual/en/function.ksort.php
Use ksort() with SORT_NUMERIC flag.
$someUnsortedArray = array("140/142" => "FirstValue", "118/120" => "SecondValue", "122/124" => "ThirdValue", "40/42" => "FourthValue");
ksort($someUnsortedArray, SORT_NUMERIC);
echo '<pre>';
print_r($someUnsortedArray);
Sample Output
Use the function uksort and pass the function a custom function/method that will do the right conversion based on your needs.
Here is the PHP manual page for he function uksort
http://php.net/manual/en/function.uksort.php
The result is the expected behaviour, because if you sort Strings in alphanumerical order 1* is always before 4*.
If you want to have it sorted by number you'll have to split your string, convert the elements to number and sort them by number.
Implementation depends on what you want to achieve. Just a list of the Keys? Then you could iterate in an foreach loop adressing the keys for example.
There won't be an "out-of-the-box" PHP Function.
$someUnsortedArray = array("5/142" => "FirstValue", "118/120" => "SecondValue", "122/124" => "ThirdValue", "40/42" => "FourthValue");
uksort($someUnsortedArray, function($a, $b) {
// to avoid manipulating them as a string ....
return ((float)$a)-((float)$b);
});
var_dump($someUnsortedArray);

how to find "http" in string from array?

In PHP I have an array like this:
array
0 => string 'open' (length=4)
1 => string 'http://www.google.com' (length=21)
2 => string 'blank' (length=5)
but it could also be like:
array
0 => string 'blank' (length=5)
1 => string 'open' (length=4)
2 => string 'http://www.google.com' (length=21)
now it is easy to find "blank" with in_array("blank", $array) but how can I see if one string is starting with "http"?
I've tried with
array_search('http', $array); // not working
array_search('http://www.google.com', $array); // is working
now everything after `http? could vary (how to write vary, varie? could be different is what I mean!)
Now do I need a regex or how can I check if http exists in array string?
Thanks for advices
"Welcome to PHP, there's a function for that."
Try preg_grep
preg_grep("/^http\b/i",$array);
Regex explained:
/^http\b/i
^\ / ^ `- Case insensitive match
| \/ `--- Boundary character
| `------ Literal match of http
`--------- Start of string
Try using the preg_grep function which returns an array of entries that match the pattern.
$array = array("open", "http://www.google.com", "blank");
$search = preg_grep('/http/', $array);
print_r($search);
Solution without regex:
$input = array('open', 'http://www.google.com', 'blank');
$output = array_filter($input, function($item){
return strpos($item, 'http') === 0;
});
Output:
array (size=1)
1 => string 'http://www.google.com' (length=21)
You can use preg_grep
$match = preg_grep("/http/",$array);
if(!empty($match)) echo "http exist in the array of string.";
or you can use foreach and preg_match
foreach($array as $check) {
if (preg_match("/http/", $check))
echo "http exist in the array of string.";
}

How to split an array by every nth appearance of a string?

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));
}

Categories