This repository has been archived by the owner on Jan 8, 2020. It is now read-only.
/
StringTrim.php
113 lines (101 loc) · 2.63 KB
/
StringTrim.php
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
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
<?php
/**
* Zend Framework (http://framework.zend.com/)
*
* @link http://github.com/zendframework/zf2 for the canonical source repository
* @copyright Copyright (c) 2005-2012 Zend Technologies USA Inc. (http://www.zend.com)
* @license http://framework.zend.com/license/new-bsd New BSD License
* @package Zend_Filter
*/
namespace Zend\Filter;
use Traversable;
/**
* @category Zend
* @package Zend_Filter
*/
class StringTrim extends AbstractFilter
{
/**
* @var array
*/
protected $options = array(
'charlist' => null,
);
/**
* Sets filter options
*
* @param string|array|Traversable $charlistOrOptions
*/
public function __construct($charlistOrOptions = null)
{
if ($charlistOrOptions !== null) {
if (!is_array($charlistOrOptions)
&& !$charlistOrOptions instanceof Traversable)
{
$this->setCharList($charlistOrOptions);
} else {
$this->setOptions($charlistOrOptions);
}
}
}
/**
* Sets the charList option
*
* @param string $charList
* @return StringTrim Provides a fluent interface
*/
public function setCharList($charList)
{
if (empty($charList)) {
$charList = null;
}
$this->options['charlist'] = $charList;
return $this;
}
/**
* Returns the charList option
*
* @return string|null
*/
public function getCharList()
{
return $this->options['charlist'];
}
/**
* Defined by Zend\Filter\FilterInterface
*
* Returns the string $value with characters stripped from the beginning and end
*
* @param string $value
* @return string
*/
public function filter($value)
{
// Do not filter non-string values
if (!is_string($value)) {
return $value;
}
if (null === $this->options['charlist']) {
return $this->unicodeTrim((string) $value);
}
return $this->unicodeTrim((string) $value, $this->options['charlist']);
}
/**
* Unicode aware trim method
* Fixes a PHP problem
*
* @param string $value
* @param string $charlist
* @return string
*/
protected function unicodeTrim($value, $charlist = '\\\\s')
{
$chars = preg_replace(
array('/[\^\-\]\\\]/S', '/\\\{4}/S', '/\//'),
array('\\\\\\0', '\\', '\/'),
$charlist
);
$pattern = '/^[' . $chars . ']+|[' . $chars . ']+$/usSD';
return preg_replace($pattern, '', $value);
}
}