File: class.stringutil.php

package info (click to toggle)
kopano-webapp-plugin-files 2.1.5%2Bdfsg1-1
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 16,540 kB
  • sloc: php: 15,863; xml: 494; java: 295; python: 72; sh: 44; makefile: 11
file content (87 lines) | stat: -rw-r--r-- 1,732 bytes parent folder | download
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
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
<?php
/**
 * Created by PhpStorm.
 * User: zdev
 * Date: 10.01.15
 * Time: 11:54
 */

namespace Files\Core\Util;


class StringUtil
{
	/**
	 * Return size to human readable filesize
	 *
	 * @static
	 * @param int $filesize in bytes
	 * @param int $decimals digits
	 *
	 * @return string human readable filesize
	 */
	static function human_filesize($bytes, $decimals = 2)
	{
		$sz = ' KMGTP';
		$factor = (int)floor((strlen($bytes) - 1) / 3);
		return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . " " . @$sz[$factor] . "B";
	}

	/**
	 * check if a string starts with a specific char
	 *
	 * @static
	 * @param string $haystack
	 * @param string $needle
	 *
	 * @return boolean true if $needle is found in $haystack
	 */
	static function startsWith($haystack, $needle)
	{
		return !strncmp($haystack, $needle, strlen($needle));
	}

	/**
	 * Creates a random string
	 *
	 * @static
	 * @param int length The length of the random string
	 *
	 * @return string a random string
	 */
	static function randomstring($length = 6)
	{
		// $chars - all allowed charakters
		$chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890";

		srand((double)microtime() * 1000000);
		$i = 0;
		$pass = "";
		while ($i < $length) {
			$num = rand() % strlen($chars);
			$tmp = substr($chars, $num, 1);
			$pass = $pass . $tmp;
			$i++;
		}
		return $pass;
	}

	/**
	 * check if a string ends with a specific char
	 *
	 * @static
	 * @param string $haystack
	 * @param string $needle
	 *
	 * @return boolean true if $haystack ends with $needle
	 */
	static function endsWith($haystack, $needle)
	{
		$length = strlen($needle);
		if ($length == 0) {
			return true;
		}

		return (substr($haystack, -$length) === $needle);
	}
}