Skip to content

Commit 5bd4ce8

Browse files
authored
Merge pull request #10 from Kdecherf/fix/srcset
2 parents d391cb3 + 36fd540 commit 5bd4ce8

File tree

2 files changed

+16
-4
lines changed

2 files changed

+16
-4
lines changed

htmLawed.php

Lines changed: 9 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -838,12 +838,19 @@ function hl_tag($t)
838838
$v = str_replace('­', ' ', (false !== strpos($v, '&') ? str_replace(['­', '­', '­'], ' ', $v) : $v)); // double-quoted char: soft-hyphen; appears here as "­" or hyphen or something else depending on viewing software
839839
if ('srcset' === $k) {
840840
$v2 = '';
841-
$pattern = "/(?:\s*[^\"',\s]+(?:\s+(?:\d+w|\d+(?:\.\d+)?x)\s*)?)/";
841+
// Following pattern tries to implement srcset spec
842+
// See https://html.spec.whatwg.org/dev/images.html#srcset-attributes
843+
// See https://html.spec.whatwg.org/#parse-a-srcset-attribute
844+
$pattern = "/(?:\s*(?:[^,\s][^\s]*[^,\s])(?:\s*\S*\s*))(?:,|$)/";
842845
preg_match_all($pattern, $v, $matches);
843846
$matches = call_user_func_array('array_merge', $matches);
844847
foreach ($matches as $k1 => $v1) {
845-
$v1 = explode(' ', ltrim($v1), 2);
848+
$v1 = explode(' ', trim($v1, ', '), 2);
846849
$k1 = isset($v1[1]) ? trim($v1[1]) : '';
850+
if ('' !== $k1 && !preg_match('/(?:\d+(?:\.\d*)?[wx])/', $k1)) {
851+
// We remove candidates with an invalid descriptor
852+
continue;
853+
}
847854
$v1 = trim($v1[0]);
848855
if (isset($v1[0])) {
849856
$v2 .= hl_prot($v1, $k) . (empty($k1) ? '' : ' ' . $k1) . ', ';

tests/HTMLawedTest.php

Lines changed: 7 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,11 +11,16 @@ public function dataForImgSrcsetAttribute()
1111
'<div><img src="a.jpg" alt="image a" srcset="a.jpg 100w, b.jpg 450w" /></div>',
1212
],
1313
'srcset with pixel ratio density' => [
14+
'<div><img src="a.jpg" alt="image a" srcset="a.jpg, b.jpg 1.5x,c.jpg 2x" /></div>',
1415
'<div><img src="a.jpg" alt="image a" srcset="a.jpg, b.jpg 1.5x, c.jpg 2x" /></div>',
1516
],
1617
'srcset with invalid descriptor' => [
1718
'<div><img src="a.jpg" alt="image a" srcset=" a.jpg , b.jpg x2" /></div>',
18-
'<div><img src="a.jpg" alt="image a" srcset="a.jpg, b.jpg, x2" /></div>',
19+
'<div><img src="a.jpg" alt="image a" srcset="a.jpg" /></div>',
20+
],
21+
'srcset with commas in resource path' => [
22+
'<div><img src="a.jpg" alt="image a" srcset="a.jpg,c_120 100w,b.jpg 450w" /></div>',
23+
'<div><img src="a.jpg" alt="image a" srcset="a.jpg,c_120 100w, b.jpg 450w" /></div>',
1924
],
2025
];
2126
}
@@ -27,6 +32,6 @@ public function testImgSrcsetAttribute($input, $expectedOutput = null)
2732
{
2833
$output = htmLawed($input);
2934

30-
$this->assertSame($output, $expectedOutput ?: $input);
35+
$this->assertSame($expectedOutput ?: $input, $output);
3136
}
3237
}

0 commit comments

Comments
 (0)