|
1
|
|
|
<?php |
|
2
|
|
|
|
|
3
|
|
|
/** |
|
4
|
|
|
* This file is part of the Axstrad library. |
|
5
|
|
|
* |
|
6
|
|
|
* (c) Dan Kempster <[email protected]> |
|
7
|
|
|
* |
|
8
|
|
|
* For the full copyright and license information, please view the LICENSE |
|
9
|
|
|
* file that was distributed with this source code. |
|
10
|
|
|
* |
|
11
|
|
|
* @author Dan Kempster <[email protected]> |
|
12
|
|
|
* @package Axstrad\Common |
|
13
|
|
|
* @subpackage Utillities |
|
14
|
|
|
* @copyright 2014-2015 Dan Kempster <[email protected]> |
|
15
|
|
|
*/ |
|
16
|
|
|
|
|
17
|
|
|
namespace Axstrad\Common\Util; |
|
18
|
|
|
|
|
19
|
|
|
|
|
20
|
|
|
/** |
|
21
|
|
|
* Axstrad\Common\Util\StrUtil |
|
22
|
|
|
*/ |
|
23
|
|
|
class StrUtil |
|
24
|
|
|
{ |
|
25
|
|
|
/** |
|
26
|
|
|
* Wraps $needle in $wrapEle HTML tags if found in $haystack. |
|
27
|
|
|
* |
|
28
|
|
|
* @param string $haystack |
|
29
|
|
|
* @param string $needle |
|
30
|
|
|
* @param string $wrapEle |
|
31
|
|
|
* @param boolean $wrapHaystackOnFailure |
|
32
|
|
|
* @return string |
|
33
|
|
|
*/ |
|
34
|
|
|
public static function wrapSubstr( |
|
35
|
|
|
$haystack, |
|
36
|
|
|
$needle, |
|
37
|
|
|
$wrapEle = null, |
|
38
|
|
|
$wrapHaystackOnFailure = false |
|
39
|
|
|
) { |
|
40
|
|
|
empty($wrapEle) && $wrapEle = "span"; |
|
41
|
|
|
|
|
42
|
|
|
if (stripos($haystack, $needle) === false && |
|
43
|
|
|
strtolower(substr($needle, -1)) == 's' |
|
44
|
|
|
) { |
|
45
|
|
|
$needle = substr($needle, 0, -1); |
|
46
|
|
|
} |
|
47
|
|
|
|
|
48
|
|
|
|
|
49
|
|
|
if (stripos($haystack, $needle) !== false) { |
|
50
|
|
|
$replace = '<'.$wrapEle.'>$0</'.$wrapEle.'>'; |
|
51
|
|
|
|
|
52
|
|
|
$return = preg_replace('/'.$needle.'/i', $replace, $haystack); |
|
53
|
|
|
} |
|
54
|
|
|
|
|
55
|
|
|
if (empty($return)) { |
|
56
|
|
|
$return = $haystack; |
|
57
|
|
|
|
|
58
|
|
|
if ($wrapHaystackOnFailure) { |
|
59
|
|
|
$return = sprintf('<%1$s>%2$s</%1$s>', $wrapEle, $haystack); |
|
60
|
|
|
} |
|
61
|
|
|
} |
|
62
|
|
|
|
|
63
|
|
|
return $return; |
|
64
|
|
|
} |
|
65
|
|
|
|
|
66
|
|
|
/** |
|
67
|
|
|
* Truncats $string to $maxLength and appends '...' |
|
68
|
|
|
* |
|
69
|
|
|
* @param string $string The string to truncate |
|
70
|
|
|
* @param $maxLength Maximum character length (excluding ellipse) of returned string. |
|
71
|
|
|
* @return string Returns $string unaltered if it's shorter then $maxLength. |
|
72
|
|
|
* Otherwise $string is returned truncated to $maxLength with '...' |
|
73
|
|
|
* appended. |
|
74
|
|
|
*/ |
|
75
|
|
|
public static function ellipse($string, $maxLength) |
|
76
|
|
|
{ |
|
77
|
|
|
if (strlen($string) > $maxLength) { |
|
78
|
|
|
return substr($string, 0, $maxLength).'...'; |
|
79
|
|
|
} |
|
80
|
|
|
return $string; |
|
81
|
|
|
} |
|
82
|
|
|
} |
|
83
|
|
|
|