Extract only email and password from text file using PHP - php

I have an array which have string kind of object I can say
Array
(
[0] => Name=xyz
[1] => Email=xyz43#gmail.com
[2] => Password=xyz#123
[3] => Address=xyz University Lucknow
[4] => City=xyz
[5] => Name=peter
[6] => Email=peter43#gmail.com
[7] => Password=peter#123
[8] => Address=address
[9] => City=bla
[10] => Name=Jack
[11] => Email=jack76#gmail.com
[12] => Password=jack123
[13] => Address=jackAddress
[14] => City=jackCity
)
desired output
Array
(
[Email] => xyz43#gmail.com
[Email] => peter43#gmail.com
[Email] => jack76#gmail.com
[Password] =>xyz#123
[Password] =>peter#123
[Password] =>jack123
)
Let me confess that I want this stuff for login purpose thank you in advance .

You can try like this
$stringArray = ['Name=xyz','Email=xyz43#gmail.com','Password=xyz#123','Address=xyz University Lucknow','Name=xyz','Email=xyz413#gmail.com','Password=xyz1#123','Address=xyz University Lucknow'];
$loginCredentials = [];
$i = 0;
foreach($stringArray as $item){
$data = explode('=', $item);
if(in_array('Email',$data) || in_array('Password',$data)){
$loginCredentials[$i][$data[0]] = $data[1];
if(isset($loginCredentials[$i]['Email']) && isset($loginCredentials[$i]['Password'])){
$i++;
}
}
}
//Output desired array
print_r($loginCredentials);

Related

I want all arrays data in one array in php

I want all arrays data in one array not all arrays in one array only the data of all arrays in one array without any other array in php. I have tried to do too many things but still don't work for me.
I also tried
json_encode
with
preg_match
But still don't work for me.
Here is my code
function fetchHashtags($getData){
$body = $getData;
$hashtag_set = [];
$array = explode('#', $body);
foreach ($array as $key => $row) {
$hashtag = [];
if (!empty($row)) {
$hashtag = explode(' ', $row);
$hashtag_set[] = '#' . $hashtag[0];
}
}
print_r($hashtag_set);
}
Output
Array
(
[0] => #Residência
[1] => #architecture
[2] => #casanaserra
[3] => #mountainhouse
[4] => #interiores
[5] => #decoration
[6] => #casanaserra
[7] => #casadecampo
[8] => #construção
[9] => #exterior
[10] => #rustico
[11] => #arpuro
[12] => #home
[13] => #riodejaneiro
[14] => #construir
[15] => #casasincriveis
[16] => #outdoor
[17] => #arquiteto
[18] => #casasincriveis
[19] => #montanhas
[20] => #archdaily
[21] => #architecturelovers
[22] => #arqlovers
[23] => #arqlove
[24] => #homedesign
[25] => #arquiteturaedecoração
)
Array
(
[0] => #We
[1] => #ascaspenvswheaton
)
Array
(
[0] => #شجریان_بشنویم...
[1] => #۰
[2] => #شجریان_بشنویم
[3] => #_
[4] => #شجریانیها
[5] => #همایون_شجریان
[6] => #مژگان_شجریان
[7] => #پرویزمشکاتیان
[8] => #موزیک
[9] => #سهراب_پورناظری
[10] => #محمدرضا_شجریان
[11] => #موزیک_ویدیو
[12] => #ایران
[13] => #ترانه_ماندگار
[14] => #تصنیف
[15] => #آهنگ_ایرانی
[16] => #هنر
[17] => #موسیقی_ایرانی
[18] => #شعروشاعری
[19] => #موسیقی_سنتی_ایران
[20] => #آواز_سنتی
[21] => #قدیمیها
[22] => #دلشدگان
[23] => #دلنشین
[24] => #سینما
[25] => #homayoun_shajarian
[26] => #music
[27] => #mohamadrezashajarian
[28] => #home
[29] => #iran
[30] => #shajarian
)
And one more thing i also want to remove some data that don't look like hashtags.
for example:
Array
(
[0] => #Residência
[1] => architecture // This should be removed
[2] => #casanaserra
[3] => mountainhouse // This also should be removed
[4] => #interiores
)
As you can see from my code you can use array_merge for merge arrays then use array_filter for filter value without # or other rules you need:
$array = [['1', '#2', '3', '#4'], ['5', '#6']];
$flatArray = array_merge(...$array);
$filteredArray = array_filter($flatArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
print_r($filteredArray);
Result:
Array (
[1] => #2
[3] => #4
[5] => #6 )
Reference:
array_merge
array_filter
str_contains
After seeing your code and the context of the situation I changed things:
Instead of use explode i used preg_split for split \n and space;
Delete array_map because you don't need it.
$array = ["
My name is Faraz shaikh i am a php developer and this my #instagram profile.Check out my #merge and my #packages with new #hashtags
#chinese #art #colors #home #harmory #peace #handmade #paintings #etsy
", "
My name is Hunain shaikh i am a php developer and this my #Facebook profile.Check out my #Berge and my #Hackages with new #tags
#english #Kite #colours #me #memory #pee #made #paints #etsafsy
"];
function fetchHashtags($getData) { // This Functions takes out the hashtags from the string and put it in to arrays.
$body = $getData;
$hashtag_set = [];
$array = preg_split('/[\s]+/', $body);
$mapArray = array_map(function($a) {
return str_replace(' ', '', $a);
}, $array);
$filteredArray = array_filter($mapArray, function($a) {
if (str_contains($a, '#')) {
return $a;
}
});
return $filteredArray;
}
$recentNumberOfPosts = 1;
$zeroPost = 0; //Get Post from 0 to recentNumberOfPosts | NOTE: default = 4
$finalArr = [];
while ($zeroPost <= $recentNumberOfPosts) {
// fetchHashtags($hashtagRecent['data'][$zeroPost]['caption']);
$finalArr[] = fetchHashtags($array[$zeroPost]);
$zeroPost++;
}
print_r(array_merge(...$finalArr));
Fiddle

Array and Mysql insert using PDO

0I have an array ($dataArray) in the following format which is created from a csv file:
The CSV is processed as follows:
function csvstring_to_array($string, $separatorChar = ',', $enclosureChar = '"', $newlineChar = "\n") {
// #author: Klemen Nagode
$array = array();
$size = strlen($string);
$columnIndex = 0;
$rowIndex = 0;
$fieldValue="";
$isEnclosured = false;
for($i=0; $i<$size;$i++) {
$char = $string{$i};
$addChar = "";
if($isEnclosured) {
if($char==$enclosureChar) {
if($i+1<$size && $string{$i+1}==$enclosureChar){
// escaped char
$addChar=$char;
$i++; // dont check next char
}else{
$isEnclosured = false;
}
}else {
$addChar=$char;
}
}else {
if($char==$enclosureChar) {
$isEnclosured = true;
}else {
if($char==$separatorChar) {
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex++;
}elseif($char==$newlineChar) {
echo $char;
$array[$rowIndex][$columnIndex] = $fieldValue;
$fieldValue="";
$columnIndex=0;
$rowIndex++;
}else {
$addChar=$char;
}
}
}
if($addChar!=""){
$fieldValue.=$addChar;
}
}
if($fieldValue) { // save last field
$array[$rowIndex][$columnIndex] = $fieldValue;
}
return $array;
}
$dataArray = csvstring_to_array( file_get_contents("ACS_MONTHLY_DUES - Jun 2020.csv"));
echo '<pre>';
print_r($dataArray);
echo '</pre>';
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
[2] => Array
(
[0] => XXXX
[1] => XXXXX
[2] => UK91002971
[3] => 61610217
[4] => XXXXXXX
[5] => XXXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 8
[10] => 243
[11] => 251
[12] => 06-06-2020
[13] => 0
[14] => 0
)
)
I need to insert it in my mysql DB using PDO. I tried the following and it is not working:
include_once('inc/connstring.inc.php');
$stmt = $conn->prepare("INSERT INTO customer(subscriber_code, subscriber_id, region,center,subscriber_name,subscriber_phone,package,stb_nos,last_month_payment,amount_due,minimum_recharge,total_payable,expiry_date,pay_amount,current_balance)
VALUES(:subscribercode, :subscriberid, :region,:center,:subscribername,:subscriberphone,:package,:stbnos,:lastmonthpayment,:amountdue,:minimumrecharge,:totalpayable,:expirydate,:payamount,:currentbalance)");
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
':region' => $row['REGION'],
':center' => $row['CENTER'],
':subscribername' => $row['SUBSCRIBERNAME'],
':subscriberphone' => $row['SUBSCRIBERPHONE'],
':package' => $row['BOUQ'],
':stbnos' => $row['STB_NOS'],
':lastmonthpayment' => $row['LAST MONTH PAYMENT'],
':amountdue' => $row['AMOUNT_DUE'],
':minimumrecharge' =>$row['MINIMUM_RECHARGE'],
':totalpayable' => $row['TOTAL_PAYABLE'],
':expirydate' => $row['EXPIRY_DATE'],
':payamount' => $row['PAY_AMOUNT'],
':currentbalance' => $row['CURRENT BALANCE']));
}
It is not working. Invalid argument supplied for foreach()
What am i doing wrong?? Requesting help from php experts...
Thanks in advance.
update:
Solved myself. Changed code to convert CSV to an associative array and now everything works fine.
Array
(
[0] => Array
(
[REGION] => XXX
[CENTER] => XXXXX
[SUBSCRIBER CODE] =>UK91002970
[SUBSCRIBER_ID] => 61610070
[SUBSCRIBERNAME] => XXXXX
[SUBSCRIBERPHONE] => XXXXXXX
[BOUQ] => UK FTA-1
[STB_NOS] => 1
[LAST MONTH PAYMENT] => 0
[AMOUNT_DUE] => 0
[MINIMUM_RECHARGE] => 221
[TOTAL_PAYABLE] => 221
[EXPIRY_DATE] => 08-06-2020
[PAY_AMOUNT] => 0
[CURRENT BALANCE] => 0
)
Your array $dataArray contains this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
[4] => SUBSCRIBERNAME
[5] => SUBSCRIBERPHONE
[6] => BOUQ
[7] => STB_NOS
[8] => LAST MONTH PAYMENT
[9] => AMOUNT_DUE
[10] => MINIMUM_RECHARGE
[11] => TOTAL_PAYABLE
[12] => EXPIRY_DATE
[13] => PAY_AMOUNT
[14] => CURRENT BALANCE
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
[4] => XXXXX
[5] => XXXXXX
[6] => UK FTA-1
[7] => 1
[8] => 0
[9] => 0
[10] => 221
[11] => 221
[12] => 08-06-2020
[13] => 0
[14] => 0
)
You try to apply values values into your SQL by using REGION, CENTER, SUBSRICBER CODE etc. but you're mixing up keys with values
This array does not include $row['REGION'], does not include $row['CENTER'] etc...
If you're doing like this:
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
':subscriberid' => $row['SUBSCRIBER_ID'],
etc...
}
then the array $dataArray would have to look like this:
Array
(
['SUBSCRIBER CODE'] => {value}
['SUBSCRIBER_ID'] => {value}
['SUBSCRIBERNAME'] => {value}
etc
)
One solution would be if (if I understand the array structure correctly) to apply keys from second and further based on first elements values
Lets say we have this:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002970
[3] => 61610070
)
[2] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002971
[3] => 61610217
)
[3] => Array
(
[0] => XXX
[1] => XXX
[2] => UK91002972
[3] => 61610218
)
)
then first element contains: ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID']
and second to fourth element contains the actual values "mapped to region, center , subscriber code, subscriber id".
A solution would be:
$dataArray = [];
$dataArray[] = ['REGION', 'CENTER', 'SUBSCRIBER CODE','SUBSCRIBER_ID'];
$dataArray[] = ['XXX', 'XXX', 'UK91002970', '61610070'];
$dataArray[] = ['XXX', 'XXX', 'UK91002971', '61610217'];
$dataArray[] = ['XXX', 'XXX', 'UK91002972', '61610218'];
$keys_apply = array_values($dataArray[0]); //get all values of first item in array
$i = 0;
foreach($dataArray as $key=>$item) {
if ($i>0) { //skip first item
$index = 0; //We know that index are 0 and above we start with zero here and
//and add one for each iteration
foreach($item as &$ik) {
//create new item with mapped key-value from first item in array but with
//the same value ($ik)
$dataArray[$key][$keys_apply[$index]] = $ik;
//Unset removes $dataArray[1][0], [1][1], [1][2] etc.
unset($dataArray[$key][$index]);
//Next element in this inner array
$index++;
}
}
$i++;
}
You would then have:
Array
(
[0] => Array
(
[0] => REGION
[1] => CENTER
[2] => SUBSCRIBER CODE
[3] => SUBSCRIBER_ID
)
[1] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002970
[SUBSCRIBER_ID] => 61610070
)
[2] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002971
[SUBSCRIBER_ID] => 61610217
)
[3] => Array
(
[REGION] => XXX
[CENTER] => XXX
[SUBSCRIBER CODE] => UK91002972
[SUBSCRIBER_ID] => 61610218
)
)
And then your original
foreach($dataArray as $row) {
$stmt->execute(array(
':subscribercode' => $row['SUBSCRIBER CODE'],
etc...
}
would work.

Reading results from PHP Facebook Graph api SDK

I am trying to get a list of all the names & id of people actually going to an event I create. Getting the list using the php graph api for facebook was the easy part and seems to work.
Code (php) the get the data:
//GET ATTENDING
$getattending = "/" . $event_id . "/attending?fields=name,id";
$req_events = new FacebookRequest($session, 'GET', $getattending);
$req_response = $req_events->execute();
$data_array = $req_response->getGraphObject()->asArray();
$counter = array_map("count", $data_array);
$count = $counter['data'];
echo "Attending: $count<BR>";
echo "<PRE>";
print_r($data_array);
echo "</PRE>";
The result:
Array (
[data] => Array
(
[0] => stdClass Object
(
[name] => Thierry Martens
[id] => 788923242
)
[1] => stdClass Object
(
[name] => Lisa Mario Laurier
[id] => 708876902536391
)
[2] => stdClass Object
(
[name] => Ramy Mahfoudhi
[id] => 735036479911364
)
[3] => stdClass Object
(
[name] => Jeremy Verriest Duroisin
[id] => 783108468420824
)
[4] => stdClass Object
(
[name] => Jonas En Svetlana Laurier
[id] => 773139856081632
)
[5] => stdClass Object
(
[name] => Maxime Demerliere
[id] => 849400761761008
)
[6] => stdClass Object
(
[name] => Jeremy Beauchamp
[id] => 10204174155667109
)
[7] => stdClass Object
(
[name] => Sari Jens Delcourte Delusinne
[id] => 10204086515874904
)
[8] => stdClass Object
(
[name] => Pieter Marysse
[id] => 10204911283045115
)
[9] => stdClass Object
(
[name] => Patrick Vanden Bosschelle
[id] => 10202907209181148
)
)
BUT i am having problems to actually gather the data itsels; i simply need the name and the id in simple array or list so i can use it in the rest of the script. Any ideas Anyone?
My second question is the php graph api seems to have a "/eventnr/attending" thing for graph 2.1; showing nr attendants to your event in question; but when i actually call it i get an error stating i need to use graph 2.1 while i uploaded the latest php sdk and can't seem to find a way to change that version. This question is not as important as the one above; but if it works i would need less code :)
Hope you guys can help me :)
!!!! GOT IT !!!!
Did look some further on here and the solutions seems to be pretty easy:
for ($x = 0; $x <= $count; $x++)
{
$names[$x] = $data_array['data'][$x]->name;
$ids[$x] = $data_array['data'][$x]->id;
}
Displays:
$names array:
Array ( [0] => Thierry Martens [1] => Lisa Mario Laurier [2] => Ramy
Mahfoudhi [3] => Jeremy Verriest Duroisin [4] => Jonas En Svetlana
Laurier [5] => Maxime Demerliere [6] => Jeremy Beauchamp [7] => Sari
Jens Delcourte Delusinne [8] => Pieter Marysse [9] => Patrick Vanden
Bosschelle [10] => )
$ids array:
Array ( [0] => 788923242 [1] => 708876902536391 [2] => 735036479911364
[3] => 783108468420824 [4] => 773139856081632 [5] => 849400761761008
[6] => 10204174155667109 [7] => 10204086515874904 [8] =>
10204911283045115 [9] => 10202907209181148 [10] => )
It's like:
$dataArray = $data_array['data'];
$firstPerson = new $dataArray[0];
echo $firstPerson->name;
echo $firstPerson->id;
Maybe you need this, though:
foreach($data_array['data'] as $a){
$o = new $a; $names[] = $o->name; $ids[] = $o->id;
}
// $names is Array of names
// $ids in Array of ids
I added your code but result is the following (empty arrays)
added code:
foreach($data_array['data'] as $a)
{
$o = new $a; $names[] = $o->name; $ids[] = $o->id;
}
echo "FIRST ELEMENT - \$data_array['data'][0]: <BR>";
print_r($data_array['data'][0]); echo "<BR><BR>";
echo "\$names array: <BR>";
print_r($names); echo "<BR><BR>";
echo "\$ids array: <BR>";
print_r($ids); echo "<BR><BR>";
Result of the echo & print_r:
FIRST ELEMENT - $data_array['data'][0]:
stdClass Object ( [name] => Thierry Martens [id] => 788923242 )
$names array:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )
$ids array:
Array ( [0] => [1] => [2] => [3] => [4] => [5] => [6] => [7] => [8] => [9] => )

find non duplicated item in an array

I have two arrays built from different directories that contain file names stripped of extensions. I want to find the ones that don't make a pair thus I merged the array to obtain the array below. How can I find the only non duplicate item in an array?
Array
(
[0] => dbbackup_2014.09.03_07_06_27
[1] => dbbackup_2014.09.03_07_07_08
[2] => dbbackup_2014.09.03_07_13_33
[3] => dbbackup_2014.09.03_07_15_24
[4] => dbbackup_2014.09.03_07_21_57
[5] => dbbackup_2014.09.03_07_22_11
[6] => dbbackup_2014.09.03_08_40_35
[7] => dbbackup_2014.09.03_08_41_36
[8] => dbbackup_2014.09.03_08_43_38
[9] => dbbackup_2014.09.04_04_59_08
[10] => dbbackup_2014.09.03_07_06_27
[11] => dbbackup_2014.09.03_07_07_08
[12] => dbbackup_2014.09.03_07_13_33
[13] => dbbackup_2014.09.03_07_15_24
[14] => dbbackup_2014.09.03_07_21_57
[15] => dbbackup_2014.09.03_07_22_11
[16] => dbbackup_2014.09.03_08_40_35
[17] => dbbackup_2014.09.03_08_41_36
[18] => dbbackup_2014.09.03_08_43_38
)
Note: it is [9]
$a = array_flip(array_filter(array_count_values($a),function($item){
return $item == 1 ? true : false;
}));
print_r($a);
Output
Array
(
[1] => dbbackup_2014.09.04_04_59_08
)
Ideone
foreach($array as $data)
{
$values=explode("_",$data);
$output[$values[1]]++;
}
foreach($output as $date=>$number)
{
if($number==1)
echo $date;
}
Output:
2014.09.04
Fiddle

Remove items from S3 objects array in php

I have an array like this:
Array
(
[0] => Accounts.csv
[1] => Book1.xlsx
[2] => Documents/
[3] => Documents/AdbWinApi.dll
[4] => Documents/AdbWinUsbApi.dll
[5] => Documents/adb.exe
[6] => Documents/boot.img
[7] => Documents/fastboot.exe
[8] => Documents/side_banner.jpg
[9] => Documents/source.properties
[10] => File Organization.docx
[11] => How to Manage Risks.docx
[12] => How to Trade Forex.docx
[13] => Ken Doc - Galad Letter Head.pdf
[14] => Ken Header.png
[15] => MX_2004_fwmx_2004_en.exe
[16] => xx.docx
[17] => asmack-master.zip
[18] => ca5rmhx7l4-Human Heart 2.7z
[19] => evasi0n7.exe
[20] => ken header.pdf
[21] => sp42471.exe
)
and I would like it to return an array like below;
Array
(
[0] => Accounts.csv
[1] => Book1.xlsx
[2] => Documents
[3] => File Organization.docx
[4] => How to Manage Risks.docx
[5] => How to Trade Forex.docx
[6] => Ken Doc - Galad Letter Head.pdf
[7] => Ken Header.png
[8] => MX_2004_fwmx_2004_en.exe
[9] => xx.docx
[10] => asmack-master.zip
[11] => ca5rmhx7l4-Human Heart 2.7z
[12] => evasi0n7.exe
[13] => ken header.pdf
[14] => sp42471.exe
)
I am using the code below;
{
private function listFiles($bucket = null , $prefix = null) {
$ls = S3::getBucket($bucket, $prefix);
if(!empty($ls)) {
foreach($ls as $l) {
$fname = str_replace($prefix,"",$l['name']);
if(!empty($fname)) {
$rv[] = $fname;
}
}
}
if(!empty($rv)) {
return $rv;
}
}
}
What changes can I make to my code to get the above results. I am using Donovan Schönknecht Amazon S3 library for codeigniter.
You could use a foreach
$newarr=array();
foreach($entries as $v)
{
if(strpos($v,'/')!==false)
{
$v=explode('/',$v);
if(isset($v[1]) && strlen($v[1])>0){}else{$newarr[]=$v[0];}
}
else { $newarr[]=$v;}
}
print_r($newarr);
Working Demo
You can overwrite the elements with $array[3] = ""; e.g. Then u have empty array-elements and then you could use a function like this:
function empty_array($array){
foreach($array as $ar => $value) {
if($value == '') {
unset($array[$ar]);
}
}
return $array;
}
$new_array = emtpy_array($old_array);

Categories