Jump to content
php.lv forumi

Recommended Posts

  • Replies 108
  • Created
  • Last Reply

Top Posters In This Topic

Posted

Laika pārveide. šodien / vakar /aizvakar un laiku (ja senāk, tad īso LV datumu un ja vēl senāk par šo gadu, tad arī gadu)

function laikaParveide($s) { //Padodam UNIX timestampu
if(strtotime('today') < $s) {
	if(date('H', $s) >= 12 && date('H', $s) <= 17) {
		return 'Šodien '.date('H:i', $s);
	}
	elseif(date('H', $s) >= 18 && date('H', $s) <= 23) {
		return 'Šovakar '.date('H:i', $s);
	}
	elseif(date('H', $s) >= 00 && date('H', $s) <= 04) {
		return 'Šonakt '.date('H:i', $s);
	}
	elseif(date('H', $s) >= 05 && date('H', $s) <= 11) {
		return 'Šorīt '.date('H:i', $s);
	}
}
elseif((strtotime('today') - 86400) < $s) {
	return 'Vakardien '.date('H:i', $s);
}
elseif((strtotime('today') - 172800) < $s) {
	return 'Aizvakar '.date('H:i', $s);
}
else {
	$menesis=array('01'=>'jan', '02'=>'feb', '03'=>'mar', '04'=>'apr', '05'=>'mai', '06'=>'jūn', '07'=>'jūl', '08'=>'aug', '09'=>'sep', '10'=>'okt', '11'=>'nov', '12'=>'dec');
	return date('j', $s).'. '.$menesis[date('m', $s)].(date('Y') > date('Y', $s) ? ' '.date('Y', $s) : '').' '.date('H:i', $s);
}
}

Posted (edited)

Pārvērš naudu vārdos

 

$money - float skaitlis

$currency - "LVL" vai "EUR"

$lang - "ru" vai "lv"

$separator - (kas atdala latus no santīmiem)

 

Ierobežojumi

Pārvērš robežās no 1.00 līdz 99.99

 

	function getMoneyInWords($money,$currency="LVL",$lang="lv",$separator=","){
	$tens['lv'] = array("Desmit","Divdesmit","Trīsdesmit","Četrdesmit","Piecdesmit","Sešdesmit","Septiņdesmit","Astoņdesmit", "Deviņdesmit");
	$teens['lv'] = array("Vienpadsmit","Divpadsmit","Trīspadsmit","Četrpadsmit","Piecpadsmit","Sešpadsmit","Septiņpadsmit","Astoņpadsmit", "Deviņpadsmit");
	$ones['lv'] = array("Viens","Divi","Trīs","Četri","Pieci","Seši","Septiņi","Astoņi", "Deviņi");

	$tens['ru'] = array("Десять","Двадцать","Тридцать","Сорок","Пятьдесят","Шестьдесят","Семьдесят","Восемьдесят","Девяносто");
	$teens['ru'] = array("Одиннадцать","Двенадцать","Тринадцать","Четырнадцать","Пятнадцать","Шестнадцать","Семнадцать","Восемнадцать", "Девятнадцать");
	$ones['ru'] = array("Один","Два","Три","Четыри","Пять","Шесть","Семь","Восемь", "Девять");

	$money_type['lv']['LVL']['santimi'] = "santīmi";
	$money_type['lv']['LVL']['lati'] = "lati";
	$money_type['lv']['LVL']['lats'] = "lats";
	$money_type['lv']['EUR']['centi'] = "centi";
	$money_type['lv']['EUR']['eiro'] = "eiro";

	$money_type['ru']['LVL']['santimi'] = "сантимов";
	$money_type['ru']['LVL']['lati'] = "латов";
	$money_type['ru']['LVL']['lats'] = "лат";		
	$money_type['ru']['EUR']['centi'] = "цента";
	$money_type['ru']['EUR']['eiro'] = "Евро";


	$ready = ""; //Gatavā virkne
	$one = false; //ja true: lats; false: lati

	list($large,$small) = explode($separator,$money);
	$large = (int)$large; //Veselās naudas, piem. eiro, lati

	if($large > 9){
		if($large > 10 && $large < 20){
			$ready = $teens[$lang][$large-11];
		}else{
			$first = substr($large,0,1);
			$second = substr($large,1,1);

			$ready = $tens[$lang][$first-1];
			if($second){
				$ready .= " " . mb_strtolower($ones[$lang][$second-1],"UTF-8");
				if($second == 1){
					$one = true;
				}
			}
		}
	}else{
		$ready = $ones[$lang][$large-1];
		if($large == 1){
			$one = true;
		}
	}

	if($currency == "EUR"){
		$ready .= " {$money_type[$lang][$currency]['eiro']}, $small {$money_type[$lang][$currency]['centi']}";
	}else{
		$ready .= " " . ($one ? $money_type[$lang][$currency]['lats'] : $money_type[$lang][$currency]['lati']) . ", $small {$money_type[$lang][$currency]['santimi']}";
	}

	return $ready;
}

Edited by briedis
Posted (edited)

Samazina attēlu, lai iekļautos norādītajos izmēros.

Pārraksta samazināto pa virsu orģinālajam.

 

	function imageResize($path,$max_width=300,$max_height=400){
	if(!file_exists($path)){
		return false;
	}

	$max_height = (int)$max_height;
	$max_width = (int)$max_width;

	$src_img = imagecreatefromjpeg($path);

	$x = imagesx($src_img);
	$y = imagesy($src_img);

	if(($x >= $y) && ($x > $max_width)){
		$picsize = $max_width; 
		$new_w = imagesx($src_img);
		$new_h = imagesy($src_img);
		$aspect_ratio = $new_h / $new_w;
		$new_w = $picsize;
		$new_h = abs($new_w * $aspect_ratio);
	}

	if(($y > $x) && ($y > $max_height)){
		$picsize = $max_height; 
		$new_w = imagesx($src_img);
		$new_h = imagesy($src_img);
		$aspect_ratio = $new_w / $new_h;
		$new_h = $picsize;
		$new_w = abs($new_h * $aspect_ratio);
	}

	$dst_img = imagecreatetruecolor($new_w,$new_h);
	imagecopyresampled($dst_img,$src_img,0,0,0,0,$new_w,$new_h,imagesx($src_img),imagesy($src_img));
	return imagejpeg($dst_img, $path, 80);
}

Edited by briedis
Posted

Nezinu cik šis ir pilnīgs, bet.. Pārbauda vai strings nav tukšs un nesatur tikai atstarpes

function navTukss($s) {
if(!empty($s)) {
	$s = trim($s);
	if(!empty($s)) {
		return true;
	}
	else {
		return false;
	}
}
else {
	return false;
}
}

Posted

1. funkcija - iegūst faila paplašinājumu

2. funkcija - pārbauda, vai fails ir attēls (tikai pēc paplašinājuma, kā jau mēs zinām, mime tips arī nav 100% drošs avots :))

 

	//Iegūstam faila paplašinājumu
function getFileExtension($file_name){
	$info = pathinfo($file_name);
	return $info['extension'];
}

//Pārbaudam, vai fails ir attēls
function isImage($file_name){
	switch(getFileExtension($file_name)){
		case "jpg" : return true;
		case "jpeg" : return true;
		case "gif" : return true;
		case "png" : return true;
		case "bmp" : return true;
	}
	return false;
}

Posted (edited)

Tā kā twittera API ir dažādi ierobežojumi uz pieprasījumu skaitu, vērtīgāk ir JSON datus iekešot lokāli (uzlabosies arī pieprasījuma ātrums), un atjaunot tikai reizi 5 minūtēs (vai līdz pirmajam apmeklētājam).

 

<?
function updateTwitter(){
	$path = "js/twitter.json"; //Vieta, kur glabājas JSON dati
	$username = "username"; //Lietotājvārds
	$entry_count = 6; //Atgriežamo ierakstu skaits
	$update_interval = 300; // 5 minūtes

	$url = "http://twitter.com/statuses/user_timeline/$username.json?callback=twitterCallback2&count=$entry_count";
	$stat = stat($path);
	$last_mod = (int)$stat[9];
	$delta_mins = time() - $last_mod;
	if($delta_mins > $update_interval){
		if($json_data = @file_get_contents($url)){ //Suppress warnings, ja neizdodas dabūt datus
			file_put_contents($path,$json_data);
		}else{
			touch($path);//Pabakstam failu, lai nav jāmēģina atkal, ja neizdevās dabūt datus
		}
	}	
}
?>

Edited by briedis
Posted

Nezinu cik šis ir pilnīgs, bet.. Pārbauda vai strings nav tukšs un nesatur tikai atstarpes

tā funkcija tiešām ir pilnīga tādā šī vārda nozīmē kā "resna/korpulenta/uzblīdusi" jeb angliski bloated :P

omg, kā tā var rakstīt!

if(!empty($s)) {
return true;
}
else {
return false;
}

ja jau empty() izdod bool, tad to var uzreiz lietot

return !empty($s);

ja vajag pārbaudīt tikai stringu

function hasStr($s) {return trim($s) != '';}

14x rindiņas vs 1x rindiņa ;) feel the difference?

 

bet ja vajag vispārīgāku pārbaudi uz dažādiem datu tipiem, tad arī to var izdarīt ar 1x statement

function hasVal($v) {return (bool) (is_string($v) ? trim($v) : $v);}  // has value - checks if $v has value

pieņemsim, ka šī ir mana funkcija šim topikam ;)

 

test it...

foreach (array(null, true, false, 0, 123, '', ' ', 'asdf', array()) as $v) echo (hasVal($v) ? 'true' : 'false') . '<br />';
/*
false
true
false
false
true
false
false
true
false
*/

vsp par tādiem nosaukumiem kā "navTukss()" - tas ir kkādā lv mentalitātes stilā 4erez noliegumu noliegšanu. imho, labāk definēt daudzmaz konstruktīvi "irVertiba()" vai "navVertiba()" (choose atkarībā no biežākā usage)

Posted (edited)

1. pārvērš baitus normālos lielumos

2. izveido SEO stringu

function mksize($bytes) {
   $symbol = array('B', 'KB', 'MB', 'GB', 'TB', 'PB', 'EB', 'ZB', 'YB');
   $exp = $converted_value = 0;
   if ($bytes > 0) {
       $exp = floor(log($bytes) / log(1024));
       $converted_value = $bytes / pow(1024, floor($exp));
   }
   return sprintf('%.2f '.$symbol[$exp], $converted_value);
}

 

function seo_string($str, $separator = '-') {
   setlocale(LC_ALL, 'en_US.UTF8');
   return str_replace(' ', $separator, trim(preg_replace('/[^ A-Za-z0-9_]/', ' ', trim(iconv('UTF-8', 'ASCII//TRANSLIT', preg_replace('/[ -]+/', '-', $str))))));
}

Edited by rausis
Posted

SEO title funkcija.

 

http://paste.php.lv/38be3112138193590d7e0428b7f2b52b?lang=php

$seotitle = $row['title'];
$seotitle = teksts_uz_url($seotitle, $l = 'lv');

.htaccess
RewriteRule ^offer/([^/\.]+)/([^/\.]+)/$ ads_item.php?id=$1&title=$2 [L]

Posted

es zinu, kur Kavacky lieto to funkciju. droši vien noder, kodējot valsts pasūtījumus ;)

// (:
function doNothing()
{
return 1;
}

class Valsts {
private $budzets, $aizdevums;
function __construct($budzets) {
	$this->budzets = $budzets;
}
public function ievaktNodoklus() {  // noslaukt tautu...
	@nodoklisParGaisaElposhanuUnParvietoshanos();
	@kaaAriCinamiesArProblemamApliekotTasArNodokliem();  // ;)
}
public function izpilditValstsFunkcijas() {  // infrastruktūras izveidošana/uzturēšana, efektīvas preču/pakalpojumu ražošanas veicināšana, izglītība, medicīna, policija, ugunsdzeseji, kultūra, ...
	if (rand(0, 9)) {  // piekāst nodokļu maksātājus
		if (rand(0, 1)) {
			doNothing(); // <--------------------------- šeit!!! :D:D:D
		}
		else {
			while ($this->budzets > 0) {
				$this->iekamptPriekshSavasPartijas();
			}
			$this->aiznemtiesNoStarptautiskajiemAizdevejiem(7000000000);
			while ($this->aizdevums > 0) {
				$this->iekamptPriekshSavasPartijas();
			}
		}
	}
	else {  // 10% varbūt tiek iztērēti arī kkam noderīgam
		@doSomethingUseful();
	}
}
private function iekamptPriekshSavasPartijas() {
	if ($this->budzets > 0) {
		$this->budzets -= 100000000;
	}
	elseif ($this->aizdevums > 0) {
		$this->aizdevums -= 100000000;
	}
}
private function aiznemtiesNoStarptautiskajiemAizdevejiem($kreditaSumma) {
	$this->aizdevums = $kreditaSumma;
}
}

$lv = new Valsts(4000000000);
$lv->ievaktNodoklus();
$lv->izpilditValstsFunkcijas();

Posted

vēl viens SEO title veids

function seo_string($string, $len = 10, $seperator = '-') {
$string = str_replace(array("ş", "Ş", "Ţ", "ţ", "ă", "î", "â"), array("s", "s", "t", "t", "a", "i", "a"), $string);  //RO translit
$string = str_replace(array("ā","č", "ē", "ģ", "ķ", "ļ", "ī", "ū", "š", "ņ", "ž"), array("a", "c", "e", "g", "k", "l", "i", "u", "s", "n", "z"), $string); //LV translit
$string = str_replace(array("Ā","Č", "Ē", "Ģ", "Ķ", "Ļ", "Ī", "Ū", "Š", "Ņ", "Ž"), array("A", "C", "E", "G", "K", "L", "I", "U", "S", "N", "Z"), $string); //LV translit CAPS LOCK
$string = str_replace(array("Ё","Ж","Ч","Ш","Щ","Э","Ю","Я","ё","ж","ч","ш","щ","э","ю","я","А","Б","В","Г","Д","Е","З","И","Й","К","Л","М","Н","О","П","Р","С","Т","У","Ф","Х","Ц","Ы","а","б","в","г","д","е","з","и","й","к","л","м","н","о","п","р","с","т","у","ф","х","ц","ь","ы"),array("JO","ZH","CH","SH","SCH","JE","JY","JA","jo","zh","ch","sh","sch","je","jy","ja","A","B","V","G","D","E","Z","I","J","K","L","M","N","O","P","R","S","T","U","F","H","C","Y","a","b","v","g","d","e","z","i","j","k","l","m","n","o","p","r","s","t","u","f","h","c","'","y"), $string); //RU translit
$string = strtolower($string);
$string = trim($string);
$string = trim(@ereg_replace("[^ A-Za-z0-9_]", " ", $string));
#$string = ereg_replace("[ tnr]+", "-", $string);
$string = str_replace(" ", $seperator, $string);
$string = @ereg_replace("[ -]+", "-", $string);

$t = explode($seperator, $string);
if(count($t)>$len) {
	$out = array_slice($t, 0, $len);
	$string = implode($seperator, $out);
};
return $string;
};

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Paste as plain text instead

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

Loading...

×
×
  • Create New...