1
|
|
|
<?php |
2
|
|
|
|
3
|
|
|
namespace Core\Traits; |
4
|
|
|
|
5
|
|
|
use Core\Constant; |
6
|
|
|
use Twig\Error\Error; |
7
|
|
|
|
8
|
|
|
/** |
9
|
|
|
* a trait with some string related helpers |
10
|
|
|
* Trait StringFunctions |
11
|
|
|
* @package Core\Traits |
12
|
|
|
*/ |
13
|
|
|
trait StringFunctions |
14
|
|
|
{ |
15
|
|
|
/** |
16
|
|
|
* does a haystack start with a needle ? |
17
|
|
|
* @param $haystack string the string to search in |
18
|
|
|
* @param $needle string the string to search for |
19
|
|
|
* @return bool |
20
|
|
|
*/ |
21
|
|
|
public function startsWith(string $haystack, string $needle): bool |
22
|
|
|
{ |
23
|
|
|
$length = strlen($needle); |
24
|
|
|
return (substr($haystack, 0, $length) === $needle); |
25
|
|
|
} |
26
|
|
|
|
27
|
|
|
/** |
28
|
|
|
* Does a haystack end with a needle |
29
|
|
|
* @param $haystack string the string to search in |
30
|
|
|
* @param $needle string the string to search for |
31
|
|
|
* @return bool |
32
|
|
|
*/ |
33
|
|
|
public function endsWith(string $haystack, string $needle): bool |
34
|
|
|
{ |
35
|
|
|
$length = strlen($needle); |
36
|
|
|
if ($length == 0) { |
37
|
|
|
return true; |
38
|
|
|
} |
39
|
|
|
|
40
|
|
|
return (substr($haystack, -$length) === $needle); |
41
|
|
|
} |
42
|
|
|
|
43
|
|
|
/** |
44
|
|
|
* Remove the tail of a string |
45
|
|
|
* @param $string string to slice apart |
46
|
|
|
* @param $tail string the string to remove |
47
|
|
|
* @return string |
48
|
|
|
*/ |
49
|
|
|
public function removeFromEnd(string $string, string $tail): string |
50
|
|
|
{ |
51
|
|
|
if ($this->endsWith($string, $tail)) { |
52
|
|
|
$string = substr($string, 0, -strlen($tail)); |
53
|
|
|
} |
54
|
|
|
return $string; |
55
|
|
|
} |
56
|
|
|
|
57
|
|
|
/** |
58
|
|
|
* remove some characters from the front of the string |
59
|
|
|
* @param string $string the string to be decapitated |
60
|
|
|
* @param string $head the head to be cut off ("OFF WITH HIS HEAD") |
61
|
|
|
* @return string |
62
|
|
|
*/ |
63
|
|
|
public function removeFromBeginning(string $string, string $head): string |
64
|
|
|
{ |
65
|
|
|
if ($this->startsWith($string, $head)) { |
66
|
|
|
$string = substr($string, strlen($head)); |
67
|
|
|
} |
68
|
|
|
return $string; |
69
|
|
|
} |
70
|
|
|
|
71
|
|
|
public function getExcerpt($text, $count=Constant::EXCERPT_WORD_COUNT){ |
72
|
|
|
if($count < 1){ |
73
|
|
|
throw new \ErrorException('excerpt length too low'); |
74
|
|
|
} |
75
|
|
|
|
76
|
|
|
$text = str_replace(" ", " ", $text); |
77
|
|
|
$string = explode(" ", $text); |
78
|
|
|
$trimed = ''; |
79
|
|
|
for ( $wordCounter = 0; $wordCounter < $count; $wordCounter++ ){ |
80
|
|
|
$trimed .= $string[$wordCounter]; |
81
|
|
|
if ( $wordCounter < $count-1 ){ $trimed .= " "; } |
82
|
|
|
else { $trimed .= "..."; } |
83
|
|
|
} |
84
|
|
|
$trimed = trim($trimed); |
85
|
|
|
return $trimed; |
86
|
|
|
} |
87
|
|
|
} |