Break strings into codes - php

I have an array of the format
array(
[0]=>x_4556v_7889;
[1]=>y_9908;
[2]=>f_5643u_7865;
)
I need to get output as
array(
[0]=> ([0] =>4556;
[1] =>7889;
)
[1]=>( [0]=>9908;)
[2] =>([0] =>5643;
[1]=>7865;
)
)
how to use strpos and find out the occurance of "_"(underscore) in string and get the next four characters in for loop.
Am getting only the first four digit code the next four digit are not getting.Kindly provide some logic.

Looks like you're trying to find all the numbers. In that case, consider trying this:
$output = array_map(function($item) {
preg_match_all("/\d+/",$item,$m);
return $m[0];
},$input);
Should work just fine :)

This is a regex free solution though..
$arr = array(
0=>'x_4556v_7889;',
1=>'y_9908;',
2=>'f_5643u_7865;'
);
$lettersarr = range('a','z');
array_unshift($lettersarr,'_');
array_unshift($lettersarr,';');
$new_arr=array_map(function ($v) use($lettersarr) {
return explode('#',wordwrap(str_replace($lettersarr,'',$v), 4, "#", true)); },$arr);
print_r($new_arr);
Demonstration

Related

How to Remove Elements from array in php after some given character?

I want to Remove all the Elements from my array which is after , but I am unable to do this.
I have an array like this => ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"]
and I want to print array something like this => ["18-08-2022","18-08-2022"]
I want to remove Elements after the ,
This is what I tried
<?php
while ($row = mysqli_fetch_array($result)) {
$Etime[] = $row["Etime"];
$Etime1[]=$row["Etime"];
$E2[]=substr($Etime1[],',',true);
}
$Etime = json_encode($Etime);
$Etime1=json_encode($Etime1);
echo $Etime1
?>
this is easy-
steps to do so-
1.Parse your array as string.
2.store that in a variable.
3. then use a if loop and use php explode funtion. explode function will seperate that string elements by the seperator in this case the "," you want to remove.
explode(string $separator, string $string)
where,
separator-The boundary string.
string-The input string.
limit
example=
$text = "hello,there";
//using explode-
var_dump( explode( ',', $input2 ) );
output=
array(2)
(
[0] => string(5) "hello"
[1] => string(5) "there"
)
more about explode() here- https://www.php.net/manual/en/function.explode.php
Here's a simple php that generates the output you want. Since you only need date bits I have provided you with only the date bits. You can get general idea from here
$arr = ["18-08-2022, 05:08:23pm","18-08-2022, 05:09:05pm"];
//
// sample output: [ "18-08-2022", "18-08-2022" ]
//
$dateMappedToYourFormat = array_map(function($dt) {
return explode(",", $dt)[0]; // getting everything before comma
}, $arr);
echo implode(",", $dateMappedToYourFormat); //to view your result

php preg match. Find elements with two values not in order

I got array like:
$array = array(
3A32,
4565,
7890,
0012,
A324,
9002,
3200,
345A,
0436
);
Then I need to find which elements has two numbers. The value of number can change.
If values were:
$n1 = 0;
$n2 = 3;
For that search preg_match() should return (3200,0436)
If values were:
$n1 = 0;
$n2 = 0;
preg_match() should return (0012,3200,9002)
Any idea?
Thanks.
I got your logic after looking multiple times on your input array as well as output based on given numbers.
Since i am not good in regular expression at all, i will go to find out answer with commonly know PHP functions.
1.Create a function which takes initial array as well as those search numbers in array form (so that you can search any number and any length of numbers).
2.Now iterate over initial array, split each value to convert to array and do array_count_value() for both split array and numbers array. now apply check and see exact match found or not?
3.Assign this match to a new array declared under the function itself.
4.Return this array at the end of function.
$n1 = 0;
$n2 = 0;
function checkValues($array,$numbers=array()){
$finalArray = [];
if(!empty($numbers)){
foreach($array as $arr){
$splitArr = str_split($arr);
$matched = true;
$count_number_Array = array_count_values($numbers);
$count_split_array = array_count_values($splitArr);
foreach($count_number_Array as $key=>$value){
if(!isset($count_split_array[$key]) || $count_split_array[$key] < $value){
$matched = false;
break;
}
}
if($matched === true){
$finalArray[] = $arr;
}
}
}
return $finalArray;
}
print_r(checkValues($array, array($n1,$n2)));
Output: https://3v4l.org/7uWfC And https://3v4l.org/Tuu5m And https://3v4l.org/fEKTO
Instead of using preg_match, you might use preg_grep and dynamically create a pattern that will match the 2 values in each order using an alternation.
^[A-Z0-9]*0[A-Z0-9]*3[A-Z0-9]*|[A-Z0-9]*3[A-Z0-9]*0[A-Z0-9]*$
The character class [A-Z0-9] matches either a char A-Z or a digit 0-9.
Regex demo | Php demo
If you want to use other characters, you could also take a look at preg_quote to handle regular expression characters.
function getElementWithTwoValues($n1, $n2) {
$pattern = "/^[A-Z0-9]*{$n1}[A-Z0-9]*{$n2}[A-Z0-9]*|[A-Z0-9]*{$n2}[A-Z0-9]*{$n1}[A-Z0-9]*$/";
$array = array(
"3A32",
"4565",
"7890",
"0012",
"A324",
"9002",
"3200",
"345A",
"0436"
);
return preg_grep($pattern, $array);
}
print_r(getElementWithTwoValues(0, 3));
print_r(getElementWithTwoValues(0, 0));
Output
Array
(
[6] => 3200
[8] => 0436
)
Array
(
[3] => 0012
[5] => 9002
[6] => 3200
)

How to output an array starting from the value with the highest character match count in php

I have been trying to match a string with the values in an array and output the array strings starting from the string with the highest character match count. for example:
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
As you can see, 'blend45', has the highest matched characters, with a total of 4 matched characters. I want to be able to output them starting from the first four highest match count, here is an example of the output i want:
blend45
book21
march
buzz
This is my first time trying to help someone, so hopefully this does the trick. I know you can probably simplify the code a little, but this is what I have.
<?php
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
$sort_array=array(); //Empty array
foreach ($array as $key => $value){
$num = similar_text($value,$string); //Using similar text to compar the strings.
$sort_array[$value] = $num; //Adding the compared number value and sring value to array.
}
arsort($sort_array, SORT_REGULAR);//Sorting the array by the larges number.
print_r ($sort_array);
//creating another foreach statement to get the output you wanted.
$count = 0;
foreach($sort_array as $key => $value){
$count++;
echo $count.". ".$key."\n";
};
?>
Results:
Array
(
[blend45] => 4
[book21] => 3
[airdrone] => 3
[march] => 2
[buzz] => 1
)
1. blend45
2. book21
3. airdrone
4. march
5. buzz
I think the levenshtein() function would be the most appropriate method to achieve your goal:
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
uasort($array, function($a, $b) use ($string) {
$aDistance = levenshtein($string, $a);
$bDistance = levenshtein($string, $b);
return ($aDistance < $bDistance) ? -1 : 1;
});
print_r($array);
// Output:
// Array
// (
// [fred] => blend45
// [july] => march
// [mike] => book21
// [ben] => buzz
// [jack] => airdrone
// )
http://php.net/levenshtein
Update Use uasort() instead of usort() to preserve the array keys.
I just noticed that my answer compares the similarity, but doesn't meet the highest character count match, so sorry for that :)
Here you are my answer. It is a bit different, because I'm using levenshtein function for finding nearest between two words.
I'm using uasort to reorder the array in way you liked.
Of course you can replace the algorithm for nearest by your function.
<?php
$array = array(
'mike'=>'book21',
'ben'=>'buzz',
'jack'=>'airdrone',
'july'=>'march',
'fred'=>'blend45'
);
$string = 'blenmaio2';
function cmp($a,$b){
global $string;
$aa=levenshtein($a, $string);
$bb=levenshtein($b, $string);
if($aa>$bb)
return 1;
elseif($bb>$aa)
return -1;
else return 0;
}
uasort($array,cmp);
?>
<pre><?= print_r($array); ?></pre>

Creating a dynamic PHP array

I am new PHP question and I am trying to create an array from the following string of data I have. I haven't been able to get anything to work yet. Does anyone have any suggestions?
my string:
Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35
I want to dynamically create an array called "My_Data" and have id display something like my following, keeping in mind that my array could return more or less data at different times.
My_Data
(
[Acct_Status] => active
[signup_date] => 2010-12-27
[acct_type] => GOLD
[profile_range] => 31-35
)
First time working with PHP, would anyone have any suggestions on what I need to do or have a simple solution? I have tried using an explode, doing a for each loop, but either I am way off on the way that I need to do it or I am missing something. I am getting something more along the lines of the below result.
Array ( [0] => Acct_Status=active [1] => signup_date=2010-12-27 [2] => acct_type=GOLD [3] => profile_range=31-35} )
You would need to explode() the string on , and then in a foreach loop, explode() again on the = and assign each to the output array.
$string = "Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35";
// Array to hold the final product
$output = array();
// Split the key/value pairs on the commas
$outer = explode(",", $string);
// Loop over them
foreach ($outer as $inner) {
// And split each of the key/value on the =
// I'm partial to doing multi-assignment with list() in situations like this
// but you could also assign this to an array and access as $arr[0], $arr[1]
// for the key/value respectively.
list($key, $value) = explode("=", $inner);
// Then assign it to the $output by $key
$output[$key] = $value;
}
var_dump($output);
array(4) {
["Acct_Status"]=>
string(6) "active"
["signup_date"]=>
string(10) "2010-12-27"
["acct_type"]=>
string(4) "GOLD"
["profile_range"]=>
string(5) "31-35"
}
The lazy option would be using parse_str after converting , into & using strtr:
$str = strtr($str, ",", "&");
parse_str($str, $array);
I would totally use a regex here however, to assert the structure a bit more:
preg_match_all("/(\w+)=([\w-]+)/", $str, $matches);
$array = array_combine($matches[1], $matches[2]);
Which would skip any attributes that aren't made up of letters, numbers or hypens. (The question being if that's a viable constraint for your input of course.)
$myString = 'Acct_Status=active,signup_date=2010-12-27,acct_type=GOLD,profile_range=31-35';
parse_str(str_replace(',', '&', $myString), $myArray);
var_dump($myArray);

Remove values with digit only from array - PHP

I have an array like so
array(
1=>hello,
2=>foo,
3=>192,
4=>keep characters AND digits like a1e2r5,
);
All I want to do is to remove rows containing digits ONLY (3=>192), and return an array like this one :
array(
1=>hello,
2=>foo,
3=>keep characters AND digits like a1e2r5,
);
I tried with array_filter but didn't get it work. Can someone show me how to do? Thanks
$data = array( 1 => "hello",
2 => "foo",
3 => "192",
4 => "keep characters AND digits like a1e2r5",
);
$result = array_filter( $data,
function($arrayEntry) {
return !is_numeric($arrayEntry);
}
);
Or using slightly more modern PHP, with arrow functions:
$result = array_filter( $data,
fn($arrayEntry) => !is_numeric($arrayEntry)
);
You could use a loop and the intval function.
$filteredArray = array();
foreach($array as $element){
//this works because PHP is weakly typed
if(intval($element) != $element){
$filteredArray[] = $element;
}
}
Are you sure you were using array_filter correctly? It's the best solution for your problem.
// named callback for backwards compatibility, but use an anonymous function
// if you have a high enough php version.
function callback($item) { return !is_numeric($item); }
$result = array_filter($a, 'callback');
print_r($result);
// optional - causes numeric keys to be in order
$result = array_values($result);
print_r($result);
Output using example input from question as $a:
Array
(
[1] => hello
[2] => foo
[4] => keep characters AND digits like a1e2r5
)
Array
(
[1] => hello
[2] => foo
[3] => keep characters AND digits like a1e2r5
)
I'm surprised no one mentioned this in any of the answers: using numeric tests is not a total solution. Using numeric tests will remove some elements containing non-digit characters if they are evaluated as numeric. Specifically, {e, -, .}
$data=array(
1=>'hello',
2=>'foo',
3=>'192',
4=>'keep characters AND digits like a1e2r5',
5=>'1.4',
6=>'-42',
7=>'1e2',
8=>'1.23e4',
);
function callback1($arrayEntry) {
return !is_numeric($arrayEntry);
}
$result = array_filter( $data, 'callback1');
echo '<pre>';
print_r($result);
echo '<hr>';
function callback2($arrayEntry) {
return !preg_match('/^[0-9]+$/', $arrayEntry);
}
$result = array_filter( $data, 'callback2');
print_r($result);

Categories