Seven flags to concise list of days of the week? - php

I have an array/string/integer of 7 flags, one for each day of the week (of a recurring event). How can I convert this to a brief list of the days?
So, for example
Given 1011001, return 'Su, T-W, Sa'.
Given 0111011, return 'M-W, F-Sa'.
What's the shortest way to accomplish this?
EDIT
For comparison, here's my own inelegant code:
<?php
function dowstring($dow) {
if ($dow == 0) return "Error";
$ddow = ["Su", "M", "T", "W", "Th", "F", "Sa"];
$t = strrev( sprintf('%07b', $dow) );
$u = str_split($t);
$out = '';
$cu = count($u);
$nn = 0; // number of days thus far counted
$v = 0; // number in the run
for($i = 0; $i < $cu; $i++) {
if ($u[$i]) {
if ($v == 0) {
$out .= ($nn) ? ", " : '';
$out .= $ddow[$i];
}
$nn++;
$v++;
}
else {
if ($v > 1) {
$out .= ($nn) ? "-" . $ddow[$i-1] : '';
}
$v = 0;
}
}
// in case Saturday is part of a run
if ($v > 1) {
$out .= ($nn) ? "-" . $ddow[$i-1] : '';
}
return $out;
}
echo "<pre>";
// testing script
for ($i = 1; $i < pow(2, 7); $i++) {
$ds = dowstring($i);
$j = strrev( sprintf("%07b", $i) );
printf("%s %s\n", $j, $ds);
}
echo "</pre>";
?>
EDIT
Another attempt, inspired by Prasanth:
function dowstring($dow) {
if ($dow == 0) return "Error";
$ddow = ["Su", "M", "T", "W", "Th", "F", "Sa"];
$t = strrev( sprintf('%07b', $dow) );
$v = array_keys( array_filter( str_split($t) ) );
$cv = count($v); $w = array();
$out = $ddow[$v[0]];
for ($i = 1; $i < $cv; $i++) $w[] = $v[$i] - $v[$i - 1] - 1;
$w = ( $cv == 1 ) ? array($w) : $w;
for ($i = 1; $i < $cv; $i++) {
if (!$w[$i - 1]) $last = $ddow[$v[$i]];
else {
if ( isset($last) ) $out .= '-' . $last;
$out .= ', ' . $ddow[$v[$i]];
unset($last);
}
}
if ($i > 1 && !$w[$i-2] ) $out .= '-' . $ddow[ $v[$i-1] ];
return $out;
}
I'd like to see something better. Anyone?

Try this:
$days=array('1'=>'Monday','2'=>'Tuesay','3'=>'Wednesday','4'=>'Thursday','5'=>'Friday','6'=>'Saturday','7'=>'Sunday');
$pattern = '1000110';
$arr1 = str_split($pattern);
$i=0;
foreach($days as $key => $tes) {
if($key - $arr1[$i] != $key) {
echo $tes;
}
$i++;
}
Adjust days array according to the sequence of days you want

Try this :
<?php
$days = array('Su','M','T','W','Th','F','Sa');
function checkConsec($d) {
for($i=0;$i<count($d);$i++) {
if(isset($d[$i+1]) && $d[$i]+1 != $d[$i+1]) {
return false;
}
}
return true;
}
$str = '0111011';
$array = array_keys(array_filter(str_split($str)));
$temp = array();
$res = array();
for($i=0;$i<count($array);$i++){
$temp[] = $array[$i];
if(checkConsec($temp) && count($temp) > 1){
$res[$temp[0]] = $days[$temp[0]]."-".$days[$temp[count($temp)-1]];
}else{
$res[$array[$i]] = $days[$array[$i]];
$temp = array();
$temp[] = $array[$i];
}
}
echo implode(",",$res);
?>

Related

Why the utf8 characters are seeming like question mark?

I have a form in my website. I am reviewing the form values on ui panel. Function is doing if the the word length is greater than 12 it puts a space to next to it. But when I print the value I am getting error if value is utf8.
$text= 'üğqwoweğofkeiasş övafevpğeüqrg qğekqrğofteölzfs';
function parser($str, $parse) {
$strlength = strlen($str);
$counter = 0;
$query = '';
if($strlength > $parse) {
for($i = 0; $i < $strlength; $i++) {
if($str[$i] != ' ') {
$counter++;
}
if($counter == $parse) {
$query.=$str[$i];
$query.=' ';
$counter = 0;
}
if($counter != $parse) {
$query.=$str[$i];
}
if($counter != $parse & $str[$i] == ' ') {
$counter = 0;
}
}
return $query;
}
else {
return $str;
}
}
echo parser($text,12);
Output is:
'üğqwoweğo ofkeiasş övafevpğe� üqrg qğekqrğoft teölzfs'
and it's not happening all the times just sometimes; I can't understand why is that.
Code:
function parser($string, $max_length = 12)
{
$chars = preg_split('//u', $string, -1, PREG_SPLIT_NO_EMPTY);
$i = 0;
foreach ($chars as $index => $char)
{
if ($char === ' ') { $i = 0; }
else { $i++; }
if ($i >= $max_length)
{
$chars[$index] = $char . ' ';
$i = 0;
}
}
return implode('', $chars);
}
$result = parser('üğqwoweğofkeiasş övafevpğeüqrg qğekqrğofteölzfs');
result: üğqwoweğofke iasş övafevpğeüqr g qğekqrğofteö lzfsuser

Find the subset of an array whose sum equal a given target using php

I am trying to implement a function below:
For example:
$a=array(1,10,25,50);
$number=15;
o/p : 15=1+1+1+1+1+10;
Done:
$a=array(1,10,25,50);
rsort($a);
$number=15;
$final = [];
$remainder = $number;
foreach($a as $num) {
do {
if($num <= $number) {
$final[] = $num;
$remainder -= $num;
}
if($remainder == 0) break;
} while($remainder >= $num);
}
echo $number . " = " . implode(' + ', $final);
Also this method:
$a=array(1,10,25,50);
rsort($a);
$number=15;
echo $number . " = ";
$final = [];
foreach($a as $num) {
if((int)($number / $num) > 0) {
$final = array_merge($final, array_fill(0, (int)($number / $num), $num));
$number -= (int)($number / $num) * $num;
}
}
echo implode(' + ', $final);
Make a recursive function for this:
function getcomb($arr,$actualNum, $total=0, $combination_array = array()){
foreach($arr as $k=>$v){
if($v > $actualNum) continue;
$shiftVal = $v;
if($total+$shiftVal <= $actualNum ){
$combination_array[] = $shiftVal;
$total += $shiftVal;
$reminder = $actualNum-$total;
//echo "<pre>combination_array";print_r($combination_array);
if($reminder <= 0){
return $shiftVal;
}else{
return $shiftVal .' + '.getcomb($arr, $actualNum,$total, $combination_array);
}
}
}
}
$a=array(1,10,25,50);
rsort($a);
$number=15;
echo $str = getcomb($a, $number);
Cleck here to check output

php - permutation - possible number

already look around but cant find what i want for PHP.
just say i have a number : 1234 ( can be splitted first into array )
and i want to get how many number combination possible for 2 digits, 3 digits , and 4 digits
for example :
possible 4 digits will be :
1234,1243,1324,1342, and so on. ( i dont know how many more )
possible 2 digits will be :
12,13,14,21,23,24,31,32,34,41,42,43
the closest one i get is :
$p = permutate(array('1','2','3','4'));
$result = array();
foreach($p as $perm) {
$result[]=join("",$perm);
}
$result = array_unique($result);
print join("|", $result);
function permutate($elements, $perm = array(), &$permArray = array()){
if(empty($elements)){
array_push($permArray,$perm); return;
}
for($i=0;$i<=count($elements)-1;$i++){
array_push($perm,$elements[$i]);
$tmp = $elements; array_splice($tmp,$i,1);
permutate($tmp,$perm,$permArray);
array_pop($perm);
}
return $permArray;
}
but how can i edit this so i can display for 3 and 2 digits ?
Thanks
i got what i want
it's from #mudasobwa link. and i edit to what i want.
<?php
$in = array(1,2,3,4,5,6);
$te = power_perms($in);
// print_r($te);
$thou=0;
$hun =0;
$pu = 0;
for($i=0;$i<count($te);$i++)
{
$jm = count($te[$i]);
for($j=0;$j<$jm;$j++)
{
$hsl[$i] = $hsl[$i] . $te[$i][$j];
}
if($hsl[$i] >=100 && $hsl[$i] < 1000 )
{
$ratus[$hun] = intval($hsl[$i]);
$hun = $hun + 1;
}
if($hsl[$i] <100 && $hsl[$i] >=10)
{
$pul[$pu] = intval($hsl[$i]);
$pu = $pu + 1;
}
if($hsl[$i] >=1000 && $hsl[$i] < 10000)
{
$th[$thou] = intval($hsl[$i]);
$thou = $thou + 1;
}
}
$th=array_unique($th);
$pul = array_unique($pul);
$ratus = array_unique($ratus);
sort($ratus);
sort($pul);
sort($th);
print_r($th);
function power_perms($arr) {
$power_set = power_set($arr);
$result = array();
foreach($power_set as $set) {
$perms = perms($set);
$result = array_merge($result,$perms);
}
return $result;
}
function power_set($in,$minLength = 1) {
$count = count($in);
$members = pow(2,$count);
$return = array();
for ($i = 0; $i < $members; $i++) {
$b = sprintf("%0".$count."b",$i);
$out = array();
for ($j = 0; $j < $count; $j++) {
if ($b{$j} == '1') $out[] = $in[$j];
}
if (count($out) >= $minLength) {
$return[] = $out;
}
}
// usort($return,"cmp"); //can sort here by length
return $return;
}
function factorial($int){
if($int < 2) {
return 1;
}
for($f = 2; $int-1 > 1; $f *= $int--);
return $f;
}
function perm($arr, $nth = null) {
if ($nth === null) {
return perms($arr);
}
$result = array();
$length = count($arr);
while ($length--) {
$f = factorial($length);
$p = floor($nth / $f);
$result[] = $arr[$p];
array_delete_by_key($arr, $p);
$nth -= $p * $f;
}
$result = array_merge($result,$arr);
return $result;
}
function perms($arr) {
$p = array();
for ($i=0; $i < factorial(count($arr)); $i++) {
$p[] = perm($arr, $i);
}
return $p;
}
function array_delete_by_key(&$array, $delete_key, $use_old_keys = FALSE) {
unset($array[$delete_key]);
if(!$use_old_keys) {
$array = array_values($array);
}
return TRUE;
}
?>

PHP Permutaion array with Priorities

Here I have a code with gives me required output but I would like to add priority order while choosing it
All possible combination code
$array = array('x2', 'y', 'm');
function depth_picker($arr, $temp_string, &$collect) {
if ($temp_string != "")
$collect []= $temp_string;
for ($i=0; $i<sizeof($arr);$i++) {
$arrcopy = $arr;
$elem = array_splice($arrcopy, $i, 1); // removes and returns the ith element
if (sizeof($arrcopy) > 0) {
depth_picker($arrcopy, $temp_string ." " . $elem[0], $collect);
} else {
$collect []= $temp_string. " " . $elem[0];
}
}
}
$collect = array();
depth_picker($array, "", $collect);
print_r($collect);
I found this code but I couldn't join them
function array_permutation(array $array)
{
$count = array_map('count', $array);
$finalSize = array_product($count);
$arraySize = count($array);
$output = array_fill(0, $finalSize, []);
$i = 0;
$c = 0;
for (; $i < $finalSize; $i++) {
for ($c = 0; $c < $arraySize; $c++) {
print $output[$i][] = $array[$c][$i % $count[$c]];
}
print "<br/>";
}
return $output;
}
$array = [['x2','x1'], ['y','k'], ['m', 'n']];
//print $output;
$output= array_permutation($array);
I am looking for making the script to output as
x2
x1
y
k
m
n
x2y
x1y
x2k
x1k
x2ym
x1ym
x2yn
x1yn
x2km
x1km
x2kn
x1kn
likewise...

PDF to XML conversion using PHP

I need help to convert PDF to XML using PHP.
There are some sites which claims to do so. But they charge for that.
I have to write my own code in PHP for that.
Being a novice in PHP I don't know how to approach this task.
So if anyone had worked on it plz help me with this.
Any help would be highly appreciated.
PDFX does PDF-to-XML conversion and it's free to use. It might be helpful in your case as it can extract things like images and captions separately.
Example input/output can be found here.
The usage page includes a simple PHP client example.
(Disclosure: It is my system.)
PDF2HTML will convert to HTML or XML (using the -xml flag), but the result is a bit of a mess. You get lots of small chunks of information about the location of fragments of text. No good of you want to extract paragraphs or sections of text. You may be able to isolate images with a suitable XPath?
If you do need paragraphs or sections of text, it appears you have to do it heuristically. Geert's blog has an interesting approach:
Isolating text runs in different zones (like header and footer)
Gathering text runs on the same ‘line’ (ignoring columns here)
Translate indentation to hierarchy (helps finding lists, provides bare table/column handling)
Merging of lines to build paragraphs
You can use this class to pars pdf into string and than work this it =)
<?php class PDF2Text2 {
var $multibyte = 4; //
var $convertquotes = ENT_QUOTES; //
var $showprogress = true; //
var $filename = '';
var $decodedtext = '';
function setFilename($filename) {
// Reset
$this->decodedtext = '';
$this->filename = $filename;
}
function output($echo = false) {
if($echo) echo $this->decodedtext;
else return $this->decodedtext;
}
function setUnicode($input) {
// 4 for unicode. But 2 should work in most cases just fine
if($input == true) $this->multibyte = 4;
else $this->multibyte = 2;
}
function decodePDF() {
// Read the data from pdf file
$infile = #file_get_contents($this->filename, FILE_BINARY);
if (empty($infile))
return "";
// Get all text data.
$transformations = array();
$texts = array();
// Get the list of all objects.
preg_match_all("#obj[\n|\r](.*)endobj[\n|\r]#ismU", $infile . "endobj\r", $objects);
$objects = #$objects[1];
// Select objects with streams.
for ($i = 0; $i < count($objects); $i++) {
$currentObject = $objects[$i];
// Prevent time-out
#set_time_limit ();
if($this->showprogress) { // echo ". ";
flush(); ob_flush();
}
// Check if an object includes data stream.
if (preg_match("#stream[\n|\r](.*)endstream[\n|\r]#ismU", $currentObject . "endstream\r", $stream )) {
$stream = ltrim($stream[1]);
// Check object parameters and look for text data.
$options = $this->getObjectOptions($currentObject);
if (!(empty($options["Length1"]) && empty($options["Type"]) && empty($options["Subtype"])) )
if ( $options["Image"] && $options["Subtype"] )
if (!(empty($options["Length1"]) && empty($options["Subtype"])) )
continue;
// Hack, length doesnt always seem to be correct
unset($options["Length"]);
// So, we have text data. Decode it.
$data = $this->getDecodedStream($stream, $options);
if (strlen($data)) {
if (preg_match_all("#BT[\n|\r](.*)ET[\n|\r]#ismU", $data . "ET\r", $textContainers)) {
$textContainers = #$textContainers[1];
$this->getDirtyTexts($texts, $textContainers);
} else
$this->getCharTransformations($transformations, $data);
}
}
}
// Analyze text blocks taking into account character transformations and return results.
$this->decodedtext = $this->getTextUsingTransformations($texts, $transformations);
}
function decodeAsciiHex($input) {
$output = "";
$isOdd = true;
$isComment = false;
for($i = 0, $codeHigh = -1; $i < strlen($input) && $input[$i] != '>'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
switch($c) {
case '\0': case '\t': case '\r': case '\f': case '\n': case ' ': break;
case '%':
$isComment = true;
break;
default:
$code = hexdec($c);
if($code === 0 && $c != '0')
return "";
if($isOdd)
$codeHigh = $code;
else
$output .= chr($codeHigh * 16 + $code);
$isOdd = !$isOdd;
break;
}
}
if($input[$i] != '>')
return "";
if($isOdd)
$output .= chr($codeHigh * 16);
return $output;
}
function decodeAscii85($input) {
$output = "";
$isComment = false;
$ords = array();
for($i = 0, $state = 0; $i < strlen($input) && $input[$i] != '~'; $i++) {
$c = $input[$i];
if($isComment) {
if ($c == '\r' || $c == '\n')
$isComment = false;
continue;
}
if ($c == '\0' || $c == '\t' || $c == '\r' || $c == '\f' || $c == '\n' || $c == ' ')
continue;
if ($c == '%') {
$isComment = true;
continue;
}
if ($c == 'z' && $state === 0) {
$output .= str_repeat(chr(0), 4);
continue;
}
if ($c < '!' || $c > 'u')
return "";
$code = ord($input[$i]) & 0xff;
$ords[$state++] = $code - ord('!');
if ($state == 5) {
$state = 0;
for ($sum = 0, $j = 0; $j < 5; $j++)
$sum = $sum * 85 + $ords[$j];
for ($j = 3; $j >= 0; $j--)
$output .= chr($sum >> ($j * 8));
}
}
if ($state === 1)
return "";
elseif ($state > 1) {
for ($i = 0, $sum = 0; $i < $state; $i++)
$sum += ($ords[$i] + ($i == $state - 1)) * pow(85, 4 - $i);
for ($i = 0; $i < $state - 1; $i++) {
try {
if(false == ($o = chr($sum >> ((3 - $i) * 8)))) {
throw new Exception('Error');
}
$output .= $o;
} catch (Exception $e) { /*Dont do anything*/ }
}
}
return $output;
}
function decodeFlate($data) {
return #gzuncompress($data);
}
function getObjectOptions($object) {
$options = array();
if (preg_match("#<<(.*)>>#ismU", $object, $options)) {
$options = explode("/", $options[1]);
#array_shift($options);
$o = array();
for ($j = 0; $j < #count($options); $j++) {
$options[$j] = preg_replace("#\s+#", " ", trim($options[$j]));
if (strpos($options[$j], " ") !== false) {
$parts = explode(" ", $options[$j]);
$o[$parts[0]] = $parts[1];
} else
$o[$options[$j]] = true;
}
$options = $o;
unset($o);
}
return $options;
}
function getDecodedStream($stream, $options) {
$data = "";
if (empty($options["Filter"]))
$data = $stream;
else {
$length = !empty($options["Length"]) ? $options["Length"] : strlen($stream);
$_stream = substr($stream, 0, $length);
foreach ($options as $key => $value) {
if ($key == "ASCIIHexDecode")
$_stream = $this->decodeAsciiHex($_stream);
elseif ($key == "ASCII85Decode")
$_stream = $this->decodeAscii85($_stream);
elseif ($key == "FlateDecode")
$_stream = $this->decodeFlate($_stream);
elseif ($key == "Crypt") { // TO DO
}
}
$data = $_stream;
}
return $data;
}
function getDirtyTexts(&$texts, $textContainers) {
for ($j = 0; $j < count($textContainers); $j++) {
if (preg_match_all("#\[(.*)\]\s*TJ[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\(.*\))\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
elseif (preg_match_all("#T[d|w|m|f]\s*(\[.*\])\s*Tj[\n|\r]#ismU", $textContainers[$j], $parts))
$texts = array_merge($texts, array(#implode('', $parts[1])));
}
}
function getCharTransformations(&$transformations, $stream) {
preg_match_all("#([0-9]+)\s+beginbfchar(.*)endbfchar#ismU", $stream, $chars, PREG_SET_ORDER);
preg_match_all("#([0-9]+)\s+beginbfrange(.*)endbfrange#ismU", $stream, $ranges, PREG_SET_ORDER);
for ($j = 0; $j < count($chars); $j++) {
$count = $chars[$j][1];
$current = explode("\n", trim($chars[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{2,4})>\s+<([0-9a-f]{4,512})>#is", trim($current[$k]), $map))
$transformations[str_pad($map[1], 4, "0")] = $map[2];
}
}
for ($j = 0; $j < count($ranges); $j++) {
$count = $ranges[$j][1];
$current = explode("\n", trim($ranges[$j][2]));
for ($k = 0; $k < $count && $k < count($current); $k++) {
if (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+<([0-9a-f]{4})>#is", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$_from = hexdec($map[3]);
for ($m = $from, $n = 0; $m <= $to; $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", $_from + $n);
} elseif (preg_match("#<([0-9a-f]{4})>\s+<([0-9a-f]{4})>\s+\[(.*)\]#ismU", trim($current[$k]), $map)) {
$from = hexdec($map[1]);
$to = hexdec($map[2]);
$parts = preg_split("#\s+#", trim($map[3]));
for ($m = $from, $n = 0; $m <= $to && $n < count($parts); $m++, $n++)
$transformations[sprintf("%04X", $m)] = sprintf("%04X", hexdec($parts[$n]));
}
}
}
}
function getTextUsingTransformations($texts, $transformations) {
$document = "";
for ($i = 0; $i < count($texts); $i++) {
$isHex = false;
$isPlain = false;
$hex = "";
$plain = "";
for ($j = 0; $j < strlen($texts[$i]); $j++) {
$c = $texts[$i][$j];
switch($c) {
case "<":
$hex = "";
$isHex = true;
$isPlain = false;
break;
case ">":
$hexs = str_split($hex, $this->multibyte); // 2 or 4 (UTF8 or ISO)
for ($k = 0; $k < count($hexs); $k++) {
$chex = str_pad($hexs[$k], 4, "0"); // Add tailing zero
if (isset($transformations[$chex]))
$chex = $transformations[$chex];
$document .= html_entity_decode("&#x".$chex.";");
}
$isHex = false;
break;
case "(":
$plain = "";
$isPlain = true;
$isHex = false;
break;
case ")":
$document .= $plain;
$isPlain = false;
break;
case "\\":
$c2 = $texts[$i][$j + 1];
if (in_array($c2, array("\\", "(", ")"))) $plain .= $c2;
elseif ($c2 == "n") $plain .= '\n';
elseif ($c2 == "r") $plain .= '\r';
elseif ($c2 == "t") $plain .= '\t';
elseif ($c2 == "b") $plain .= '\b';
elseif ($c2 == "f") $plain .= '\f';
elseif ($c2 >= '0' && $c2 <= '9') {
$oct = preg_replace("#[^0-9]#", "", substr($texts[$i], $j + 1, 3));
$j += strlen($oct) - 1;
$plain .= html_entity_decode("&#".octdec($oct).";", $this->convertquotes);
}
$j++;
break;
default:
if ($isHex)
$hex .= $c;
elseif ($isPlain)
$plain .= $c;
break;
}
}
$document .= "\n";
}
return $document;
}}?>

Categories