Skip to content

Commit 336b816

Browse files
author
Alexander Guz
authored
Merge pull request #19 from sanmai/escape_once
escape should use htmlentities; escape_once should simply work
2 parents 7fbf843 + d00f98a commit 336b816

File tree

2 files changed

+13
-32
lines changed

2 files changed

+13
-32
lines changed

src/Liquid/StandardFilters.php

Lines changed: 6 additions & 27 deletions
Original file line numberDiff line numberDiff line change
@@ -133,42 +133,21 @@ public static function raw($input) {
133133
* @return string
134134
*/
135135
public static function escape($input) {
136-
137-
return is_string($input) ? str_replace(array('&', '>', '<', '"', "'"), array('&amp;', '&gt;', '&lt;', '&quot;', '&#39;'), $input) : $input;
138-
136+
return is_string($input) ? htmlentities($input, ENT_QUOTES) : $input;
139137
}
140-
141-
138+
139+
142140
/**
143-
* Escape a string once
141+
* Escape a string once, keeping all previous HTML entities intact
144142
*
145143
* @param string $input
146144
*
147145
* @return string
148146
*/
149147
public static function escape_once($input) {
150-
151-
preg_match('/["><\']|&(?!([a-zA-Z]+|(#\d+));)/', $input, $matches);
152-
153-
if (sizeof($matches) > 0){
154-
155-
$pos = strpos($input, $matches[0]);
156-
if ($pos !== false) {
157-
158-
$partial = substr($input, 0, $pos + 1);
159-
$remaining = substr($input, $pos + 1);
160-
161-
$partial = str_replace(array('&', '>', '<', '"', "'"), array('&amp;', '&gt;', '&lt;', '&quot;', '&#39;'), $partial);
162-
163-
$input = $partial.$remaining;
164-
165-
}
166-
167-
}
168-
169-
return $input;
148+
return is_string($input) ? htmlentities($input, ENT_QUOTES, null, false) : $input;
170149
}
171-
150+
172151

173152
/**
174153
* Returns the first element of an array

tests/Liquid/StandardFiltersTest.php

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -118,19 +118,21 @@ public function testRaw()
118118

119119
public function testEscape() {
120120
$data = array(
121-
"one Word's not" => "one Word&#39;s not",
122-
3 => 3,
121+
"one Word's not" => "one Word&#039;s not",
122+
"&><\"'" => "&amp;&gt;&lt;&quot;&#039;",
123123
);
124124

125125
foreach ($data as $element => $expected) {
126126
$this->assertEquals($expected, StandardFilters::escape($element));
127127
}
128128
}
129-
129+
130130
public function testEscapeOnce() {
131131
$data = array(
132-
"one Word's not 'twas" => "one Word&#39;s not 'twas",
133-
3 => 3,
132+
"<b><script>alert()</script>" => "&lt;b&gt;&lt;script&gt;alert()&lt;/script&gt;",
133+
"a < b & c" => "a &lt; b &amp; c",
134+
"a &lt; b &amp; c" => "a &lt; b &amp; c",
135+
"&lt;\">" => "&lt;&quot;&gt;",
134136
);
135137

136138
foreach ($data as $element => $expected) {

0 commit comments

Comments
 (0)