how to find does not match item by regular expression - php

I have comma separated values in my table column and I have to separate new values from the old ones.
My code is
$a = '1,2,3,4';
$b = '1,2';
if(preg_match("/[^$b]/",$a,$matches)){
print_r($matches);
};
I want to find 3,4 , but I can't do it.

You really shouldn't use regular expressions for that. PHP has good functions to calculate intersections:
$a = explode(',', '1,2,3,4');
$b = explode(',', '1,2');
print_r(array_values(array_diff($a, $b)));
See also: array_diff()
Note that this would also work for the following example:
$a = '1,2,3,4';
$b = '1,3';
// outcome must be: 2, 4

use preg_match_all instead of preg_match
$a = '1,2,3,4,10';
$b = '1,2';
if(preg_match_all("/[^$b](.*)/",$a,$matches)){
print_r($matches);
};
output
Array
(
[0] => Array
(
[0] => 3,4,10
)
[1] => Array
(
[0] => ,4,10
)
)

Related

How To Keep Original Key on Array Merge

I have two dynamic associated array and I am trying to merge them into one array BUT I need to keep the original keys as the orginal arrays but in return I am getting [0] for A which I need to keep it [1] as it was in array $a
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
Array (
[0] => A
[1] => B
[2] => C
[n] => 5 )
In order to preserve keys of your array you need to use + operator over here like as
$a = ["1"=>"A", "2"=>"B", "3"=>"C"];
$b = ["n"=>"5"];
$c = $a + $b;
print_r($c);
You can check PHP Manuals Example #2 Simple array_merge() example
i am not a php developer. so there could be better answers out there
the php documentation says that numerical keys are new numbered. i think that even a string as key with a nummeric value is interpretet as number.
can you try this (not the added 'a' on the nummeric keys):
$a = ["1a"=>"A", "2a"=>"B", "3a"=>"C"];
$b = ["n"=>"5"];
$c = array_merge($a,$b);
print_r($c);
it is not clean code, but after this you can "remove" the 'a' and you have your numeric key

PHP SPL RegexIterator removes unmatched elements from array

I have array with some strings and i want to use RegexIterator to replace some stuff on matched string but to also leave un-matched strings in array.
Here is my code:
$a = new ArrayIterator(array('LeaveThisInArray','value1', 'value2'));
$i = new RegexIterator($a, '/^(value)(\d+)/', RegexIterator::REPLACE);
$i->replacement = '$2:$1';
print_r(iterator_to_array($i));
And i get this as output:
Array
(
[0] => 1:value
[1] => 2:value
)
But what i wanted is this:
Array
(
[0] => LeaveThisInArray
[1] => 1:value
[2] => 2:value
)
Is there any flag i can set or something, because i cant find much in the spl documentation.
You can try with preg_replace
sample code:
$re = "/^(value)(\\d+)/m";
$str = "LeaveThisInArray\nvalue1\nvalue2";
$subst = '$2:$1';
$result = preg_replace($re, $subst, $str);
Here is online demo
Try with ^(value)(\d*) in your existing code.
The closest I can think about for this right now is like this:
$a = new ArrayIterator(array('LeaveThisInArray','value1', 'value2'));
$i = new RegexIterator($a, '/^(?:(value)(\d+))?/', RegexIterator::REPLACE);
$i->replacement = '$2$1';
print_r(iterator_to_array($i));

Remove duplicated elements of associative array in PHP

$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other'),
);
If it is duplicated removed it, so the result is as follows:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other')
);
Could any know to do this?
Thanks
Regardless what others are offering here, you are looking for a function called array_uniqueDocs. The important thing here is to set the second parameter to SORT_REGULAR and then the job is easy:
array_unique($result, SORT_REGULAR);
The meaning of the SORT_REGULAR flag is:
compare items normally (don't change types)
And that is what you want. You want to compare arraysDocs here and do not change their type to string (which would have been the default if the parameter is not set).
array_unique does a strict comparison (=== in PHP), for arrays this means:
$a === $b TRUE if $a and $b have the same key/value pairs in the same order and of the same types.
Output (Demo):
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
First things first, you can not use plain array_unique for this problem because array_unique internally treats the array items as strings, which is why "Cannot convert Array to String" notices will appear when using array_unique for this.
So try this:
$result = array(
0=>array('a'=>1,'b'=>'Hello'),
1=>array('a'=>1,'b'=>'other'),
2=>array('a'=>1,'b'=>'other')
);
$unique = array_map("unserialize", array_unique(array_map("serialize", $result)));
print_r($unique);
Result:
Array
(
[0] => Array
(
[a] => 1
[b] => Hello
)
[1] => Array
(
[a] => 1
[b] => other
)
)
Serialization is very handy for such problems.
If you feel that's too much magic for you, check out this blog post
function array_multi_unique($multiArray){
$uniqueArray = array();
foreach($multiArray as $subArray){
if(!in_array($subArray, $uniqueArray)){
$uniqueArray[] = $subArray;
}
}
return $uniqueArray;
}
$unique = array_multi_unique($result);
print_r($unique);
Ironically, in_array is working for arrays, where array_unique does not.

Removing duplicates with array_unique giving wrong result

i have two array and i want to make unique array with single array
for example i have $a=array(3); and $b=array(1,2,3) so i want $c=array(1,2,3)
i made a code like:
$a=array(3);
$b=explode(',','1,2,3');
$ab=$a+$b;
$c=array_unique ($ab);
print_r($c);
it gives me Array ( [0] => 3 [1] => 2 )
but i want to Array ( [0] => 1 [1] => 2 [2] => 3 )
$a = array(1,2,3,4,5,6);
$b = array(6,7,8,2,3);
$c = array_merge($a, $b);
$c = array_unique($c);
The operation
$ab = $a + $b
Is giving you a result you did not expect. The reason for this behaviour has been explained previously at PHP: Adding arrays together
$ab is Array ( [0] => 3 [1] => 2 [2] => 3 )
The + operator appends elements of remaining keys from the right
handed array to the left handed, whereas duplicated keys are NOT
overwritten.
array_merge provides a more intuitive behaviour.
Array merge, man. Array merge.
Anyway, as this answer for similar question ( https://stackoverflow.com/a/2811849/223668 ) tells us:
The + operator appends elements of remaining keys from the right handed array to the left handed, whereas duplicated keys are NOT overwritten.
If you have numeric keys (as in standard tables), they are for for sure duplicate in both arrays and the result is far from desired.
So the code should look like that:
$c = array_unique(array_merge($a, $b));
You need to use this array_merge to concat two array.
http://www.php.net/manual/en/function.array-merge.php
not
$ab = $a + $b

PHP: How to sort values of an array in alphabetical order?

I want to sort values of an array in alphabetical order in PHP. If all values started with same character then they should be sorted using second character and so on. Ignore case sensitive.
For Example:
before:
values[0] = "programming";
values[1] = "Stackoverflow";
values[2] = "question";
values[3] = "answers";
values[4] = "AA Systems";
after:
values[0] = "AA Systems";
values[1] = "answers";
values[2] = "programming";
values[3] = "question";
values[4] = "Stackoverflow";
I have found some algorithms but I want a way that is fast and with small number of statements. Ignoring case sensitive is special for me. Thanks.
See
natcasesort: http://www.php.net/manual/en/function.natcasesort.php
usort: http://www.php.net/manual/en/function.usort.php with a comparator function that compares strtolower(a) and strtolower(b).
Your example makes two assumptions:
That you are only dealing with simple, 1-dimensional arrays.
That after sorting alphabetically, your index will update so that the first element alphabetically will be assigned key 0 and so forth.
Given those parameters, your simplest solution is to use the array method sort(). With your example:
$values[0] = "programming";
$values[1] = "Stackoverflow";
$values[2] = "question";
$values[3] = "answers";
$values[4] = "AA Systems";
sort($values);
Which will result in the following:
Array {
[0] => AA Systems
[1] => Stackoverflow
[2] => answers
[3] => programming
[4] => question
}
There are other array sorting functions that might be a better fit. For instance, the simple one I use above puts upper-case in front of lower-case, so if you had "security" as an item (all lower-case) it would go after "Stackoverflow" since the upper-case s would take precedence over se vs. st. To sort without case-sensitivity, you could use natcasesort(), which would produce the following with the given array:
Array {
[0] => AA Systems
[1] => answers
[2] => programming
[3] => question
[4] => Stackoverflow
}
As of version 5.4.0, you can just use any of the sort, asort, ksort, etc. functions and pass the SORT_FLAG_CASE flag.
sort( $array, SORT_FLAG_CASE ); // Non-associative array
asort( $array, SORT_FLAG_CASE ); // Associative array
ksort( $array, SORT_FLAG_CASE ); // Associative array, sort by indices
If you've got an older version and aren't ready to update (or can't), you can use natcasesort as others have mentioned, but also the uasort and ksort variants with strcasecmp as the custom function:
natcasesort( $array ); // Non-associative array
uasort( $array, 'strcasecmp' ); // Associative array
uksort( $array, 'strcasecmp' ); // Associative array, sort by indices
You can apply the same concept to any of the other sorting functions.
You can use uasort(): http://php.net/manual/en/function.uasort.php
uasort( $arr, 'strcasecmp' );
The second argument is a function, which compares values. The function must return -1, 0, or 1. Here's a template, which you can use for your custom functions.
function cmp( $a, $b ) {
if ( $a == $b ) return 0;
elseif ( $a > $b ) return 1;
elseif ( $a < $b ) return -1;
}
uasort( $arr, 'cmp' );
After sorting you might want to reset array indexes.
$arr = array_values( $arr );

Categories