I have the following code:
$Field = $FW->Encrypt("Test");
echo "<pre>";
print_r($Field);
echo "</pre>";
# $IV_Count = strlen($Field['IV']);
# $Key_Count = strlen($Field['Key']);
# $Cipher_Count = strlen($Field['CipheredText']);
foreach ($Field AS $Keys => $Values){
echo $Keys."Count = ".strlen($Values)."<br><br>";
}
The output is as:
Array
(
[CipheredText] => x2nelnArnS1e2MTjOrq+wd9BxT6Ouxksz67yVdynKGI=
[IV] => 16
[Key] => III#TcTf‡eB12T
)
CipheredTextCount = 44
IVCount = 2
KeyCount = 16
The IV/KeyCount is always returning the same value regardless of the input. But the CipheredTextCount changes depending on the input.. For example:
$Field = $FW->Encrypt("This is a longer string");
The foreach loop returns:
CipheredTextCount = 64
IVCount = 2
KeyCount = 16
and now for my question. Lets take the first example with the TextCount of 44
How can I split a string after implode("",$Field); to display as the original array? an example would be:
echo implode("",$Field);
Which outputs:
ijGglH/vysf52J5aoTaDVHy4oavEBK4mZTrAL3lZMTI=16III#TcTf‡eB12T
Based on the results from the strlen?
It is possible to store the count of the first $Cipher_Count in a database for a reference
My current setup involves storing the key and IV in a seperate column away from the ciphered text string.. I need this contained within one field and the script handles the required information to do the following:
Retrieve The long string > Split string to the original array > Push
array to another function > decrypt > return decoded string.
Why not use serialize instead? Then when you get the data out of the database, you can use unserialize to restore it to an array.
$Combined_Field = implode("",$Field);
echo $str1 = substr($Combined_Field, 0, $Cipher_Count)."<br><br>";
echo $str2 = substr($Combined_Field,$Cipher_Count,$IV_Count)."<br><br>";
echo $str3 = substr($Combined_Field, $IV_Count+$Cipher_Count,$Key_Count);
Or use a function:
function Cipher_Split($Cipher, $Cipher_Count, $KeyCount, $IVCount){
return array(
"Ciphered Text" => substr($Cipher,0,$Cipher_Count),
"IV" => substr($Cipher,$Cipher_Count,$IVCount),
"Key" => substr($Cipher,$IVCount+$Cipher_Count,$KeyCount)
);
}
Related
I need one help.i need to separate numeric value from character using PHP.I am explaining my code below.
$subcatid=a1,a2,4,5
here i have some value with comma separator i need here separate numeric value(i.e-4,5) first and push them into a array then i have to separate rest numeric value from character(i.e-1 from a1,2 from a2) and push those separated value into another array.Please help me.
Try this
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
$onlynum_subcatid = array_filter($subcatid_arr, 'is_numeric');
$onlynum = implode(",",$onlynum_subcatid );
echo "Only Number : ".$onlynum;
$notnum_subcatid = array_diff($subcatid_arr,$onlynum_subcatid );
$notnum = implode(",",$notnum_subcatid );
echo "\nNot Number : ".$notnum;
?>
Output is :
Only Number : 4,5
Not Number : a1,a2
check here : https://eval.in/539059
Use this code
$subcatid="a1,a2,4,5";
$strArray = explode(',',$subcatid);
$intArr = array();
foreach($strArray as $key=>$value):
if(preg_match('/^[0-9]*$/',$value)):
$intArr[]=$value;
else:
$str2Arr = str_split($value);
foreach($str2Arr as $keyStr=>$lett):
if(preg_match('/^[0-9]*$/',$lett)):
$intArr[]=$lett;
endif;
endforeach;
endif;
endforeach;
var_dump($intArr);
in this code you can expect your result. Do process with the $number, $char array as required
<?php
$subcatid="a1,a2,4,5";
$subcatid_arr = explode(",",$subcatid);
for($i=0;$i<sizeof($subcatid_arr);$i++){
if(is_numeric($subcatid_arr[$i])){
$number[]=$subcatid_arr[$i];
}
else{
$char[]=$subcatid_arr[$i];
}
}
print_r($number);// 4,5
print_r($char);// a1,a2
?>
If I am understanding correctly, you want to put all of the original numeric values into a single array and then filter just the numeric parts of the leftovers and put them in to a second array.
If this is correct then I believe this should do what you want.
<?php
$subcatid = 'a1,a2,4,5';
$subcat_array = explode(",",$subcatid);
$subNums1 = [];
$subNums2 = [];
foreach($subcat_array as $item) {
if(is_numeric($item)) {
// This pushes all numeric values to the first array
$subNums1[] = $item;
} else {
// This strips out everything except the numbers then pushes to the second array
$subNums2[] = preg_replace("/[^0-9]/","",$item);
}
}
print_r($subNums1);
print_r($subNums2);
?>
This will return:
Array (
[0] => 4
[1] => 5
)
Array (
[0] => 1
[1] => 2
)
I am creating lines of text to be consumed by another layer in my application. The lines are:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027],
What is the fastest/easiest way to remove the trailing comma from the last line of text?
I'm expecting something like this:
['Jun 13',529],
['Jul 13',550],
['Aug 13',1005],
['Sep 13',1021],
['Oct 13',1027]
Actual Code:
$i = 0;
while($graph_data = $con->db_fetch_array($graph_data_rs))
{
$year = $graph_data['year'];
$month = $graph_data['month'];
$count = $graph_data['count'];
$total_count = $graph_data['total_count'];
// for get last 2 digits of year
$shortYear = substr($year, -2, 2);
// for get month name in Jan,Feb format
$timestamp = mktime(0, 0, 0, $month, 1);
$monthName = date('M', $timestamp );
$data1 = "['".$monthName.' '.$shortYear."',".$total_count."],";
$i++;
}
If you have that array in a variable and want a string, you can use implode to get a string separated by a glue char.
If you already have an string, you can use rtrim to remove the last char to the right of the string.
If you have an array, where the value is a string ['Oct 13',1027] (ending in a comma), you have the same options above and:
You can use array_walk with some of the mentioned functions
You can get the last element, and use rtrim on it like the code below:
Example of code using rtrim on a array of strings:
<?php
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$lastIndex = count($values)-1;
$lastValue = $values[$lastIndex];
$values[$lastIndex] = rtrim($lastValue, ',');
<?php
$arr = array(
"['Jun 13',529],",
"['Jul 13',550],"
);
$arr[] = rtrim(array_pop($arr), ', \t\n\r');
print_r($arr);
// output:
// Array
// (
// [0] => ['Jun 13',529],
// [1] => ['Jul 13',550]
// )
Make it an actual array, and implode. Not really sure what is is going to be (if json:you can do even better and not make the values themselves fake-arrays, but this is left as an exersize to the reader).
$yourData = array();
while(yourloop){
//probaby something like: $yourData = array($monthName=>$total_count);
$yourData[] = "['".$monthName.' '.$shortYear."',".$total_count."]";
}
//now you have an actual array with that data, instead of a fake-array that's a string.
//recreate your array like so:
$data1 = implode(','$yourData);
//or use json_encode.
Something similar to #srain but using array_push.
$values = array("['Oct 13',1027],", "['Oct 13',1027],");
$last = array_pop($values); //pop last element
array_push( $values, rtrim($last, ',') ); //push it by removing comma
var_dump($values);
//output
/*
array
0 => string '['Oct 13',1027],' (length=16)
1 => string '['Oct 13',1027]' (length=15)
*/
#ElonThan was right and so was #BenFortune. This is an XY Problem, and none of the other answers are giving you the best advice -- "Never craft your own json string manually".
You think you just need to remove the final comma from your textual output so that it creates something that javascript can parse as an indexed array of indexed arrays.
What you should be doing is creating a multidimensional array then converting that data into a json string. PHP has a native function that does exactly this AND it guarantees that you will have a valid json string (because it will escape characters as needed).
I'll demonstrate how to adjust your script based on your while() loop.
$result = [];
while ($row = $con->db_fetch_array($graph_data_rs)) {
$result[] = [
date('M y', strtotime($row['year'] . '-' . $row['month'])),
$row['total_count']
];
}
echo json_encode($result, JSON_PRETTY_PRINT);
Here is an online demo that re-creates your query's result set as an input array, then replicates the loop and result generation. https://3v4l.org/cG66l
Then all you have to do is echo that string into your rendered html document's javascript where required.
There is a string variable containing number data , say $x = "OP/99/DIR"; . The position of the number data may change at any circumstance by user desire by modifying it inside the application , and the slash bar may be changed by any other character ; but the number data is mandatory. How to replace the number data to a different number ? example OP/99/DIR is changed to OP/100/DIR.
$string="OP/99/DIR";
$replace_number=100;
$string = preg_replace('!\d+!', $replace_number, $string);
print $string;
Output:
OP/100/DIR
Assuming the number only occurs once:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith);
To change the first occurance only:
$content = str_replace($originalText, $numberToReplace, $numberToReplaceWith, 1);
Using regex and preg_replace
$x="OP/99/DIR";
$new = 100;
$x=preg_replace('/\d+/e','$new',$x);
print $x;
The most flexible solution is to use preg_replace_callback() so you can do whatever you want with the matches. This matches a single number in the string and then replaces it for the number plus one.
root#xxx:~# more test.php
<?php
function callback($matches) {
//If there's another match, do something, if invalid
return $matches[0] + 1;
}
$d[] = "OP/9/DIR";
$d[] = "9\$OP\$DIR";
$d[] = "DIR%OP%9";
$d[] = "OP/9321/DIR";
$d[] = "9321\$OP\$DIR";
$d[] = "DIR%OP%9321";
//Change regexp to use the proper separator if needed
$d2 = preg_replace_callback("(\d+)","callback",$d);
print_r($d2);
?>
root#xxx:~# php test.php
Array
(
[0] => OP/10/DIR
[1] => 10$OP$DIR
[2] => DIR%OP%10
[3] => OP/9322/DIR
[4] => 9322$OP$DIR
[5] => DIR%OP%9322
)
i have multidimension array
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
then i explode $a
$array_a = explode("|", $a);
//loop
for($i=0;$i<=count($arr_a)-1;$i++){
arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
echo $id." have access ".$access;
}
}
//result
0 have access 5
1 have access add
0 have access 4
1 have access edit
0 have access 6
1 have access add
0 have access 6
1 have access edit
0 have access 19
1 have access add
0 have access 19
1 have access delete
0 have access 19
1 have access view
//-end result
the problem is :
how i can make the result like this
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
I think Regex would be a better solution in this case, in case you haven't considered using it.
Sample (Tested):
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$result = array();
// match each pair in the input
if (preg_match_all('/(\\d+)\\,(.*?)(\\||$)/m', $a, $matches)){
foreach( $matches[1] as $match_index => $match ){
$result[$match][] = $matches[2][$match_index];
}
}
// loop through the results and print in desired format
foreach( $result as $entry_index => $entry ){
echo "$entry_index have access " . implode( ',', $entry ) . "\n";
}
output:
5 have access add
4 have access edit
6 have access add,edit
19 have access add,delete,view
Using regex simplifies the code and also makes it somewhat easier to change the format of the input that is supported.
The $result array ended up with a hash map using your numeric ids as the keys and arrays of permissions (add, delete, etc) as the value for each key.
Try this one (tested):
// intial data
$strAccess = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
// build access array
$arrayAccess = array();
$tmpList = explode('|', $strAccess);
foreach($tmpList as $access)
{
list($idUser, $right) = explode(',', $access);
if (!isset($arrayAccess[$idUser]))
$arrayAccess[$idUser] = array();
$arrayAccess[$idUser][] = $right;
}
// print it out
foreach($arrayAccess as $idUser => $accessList)
echo $idUser." has access ".implode(",", $accessList)."\n";
You can use counter something like
$count5=0;
foreach($arr_b as $id => $access){
if($access=='5'){
$count5++;
}
echo $id." have access ".$count5;
}
$a = "5,add|4,edit|6,add|6,edit|19,add|19,delete|19,view";
$array_a = explode("|". $a);
//loop
$aRights = array();
for($i=0;$i<=count($arr_a)-1;$i++){ $arr_b = explode(",", $arr_a[$i]);
foreach($arr_b as $id => $access){
$aRights[$id][] = $access;
}
}
foreach( $aRights as $id=>$rightsList){
echo $id." have access ";
$i=1;
foreach($rightsList as $r){
echo $r;
if($i != count($rightsList)) echo ",";
$i++;
}
}
What about something like hashmapping:
$tobegenerated = array();
$a = explode(yourdelimiter,yourstring);
foreach ($a as $cur)
{
$b = explode(delimiter,$cur);
$tobegenerated[$cur[0]] = $cur[1];
}
//Print hashmap $tobegenerated
This should work, remember that in php arrays are also hash maps
Edit 1:
Arrays in PHP are hash maps. A hash map can be interpreted as an array where keys can be anything and value can be anything too. In this case, you would like to use a hash map because you need to bind values that are "outside" the range of the array (even if they are ints). So a hash map is exactly what you want, allowing to specify anything as a key.
How a hash map work is something that you can search on google or on wikipedia. How arrays work in php can be found here
Hope my title explains it ok! Here's more detail:
I'm creating an array which stores keys & their values. Eg.
test1 = hello
test2 = world
test3 = foo
What is the cleanest way of working out what to call the next key? Let's say I will know the first part is 'test', but I don't know what the highest value number is. Obviously in this case I want it to be called 'test4'.
In the example below I want the next key to be 'test46', as it is the next highest value:
test6 = blah
test45 = boo
test23 = far
This sounds like you should be using an array with numerical indexes instead.
You could however use some code like this...
$arr = array('test6', 'test45', 'test23');
$max = 0;
foreach($arr as $value) {
$number = filter_var($value, FILTER_SANITIZE_NUMBER_INT);
$max = max($max, $number);
}
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad.
Implementation of #alex answer without using a loop:
$arr = array('test6', 'test45', 'test23');
$max = max(filter_var_array($arr, FILTER_SANITIZE_NUMBER_INT));
$newKey = 'test' . ++$max; // string(6) "test46"
CodePad
This data structure would be better stored as an array.
$test = array();
$test[] = 'hello';
$test[] = 'world';
$test[] = 'foo';
You then don't need to know the highest number to add a new item, just use the empty brackets syntax (shown above) to add an item to the end of the array.
You then have access to a wealth of array functions that PHP gives you to work with your data: http://php.net/manual/en/ref.array.php
When you want to get item 43 from the array, use:
echo $test[42];
Arrays are counted from 0 rather than 1, so item 43 will have an index of 42.
What are you using that for? If numbering the array is a must-have, just use a simple numerical indexed array instead, and simply prepend the key with "test" if you need it to show up as "test1":
<?php
$array = array(
6 => 'blah',
45 => 'boo',
23 => 'bar'
);
$array[] = 'new';
echo $array[46] . "\n"; // this is 'new'
foreach( $array as $key => $value ) {
echo "test$key = $value<br />\n"; // test6 = blah
}