Skip to content

Commit 8e21075

Browse files
committed
Feature: Escaping array dot notation
1 parent 50ed11f commit 8e21075

3 files changed

Lines changed: 37 additions & 1 deletion

File tree

system/Helpers/array_helper.php

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -26,7 +26,11 @@
2626
*/
2727
function dot_array_search(string $index, array $array)
2828
{
29-
$segments = explode('.', rtrim(rtrim($index, '* '), '.'));
29+
$segments = preg_split('/(?<!\\\)\./', rtrim($index, '* '), 0, PREG_SPLIT_NO_EMPTY);
30+
31+
$segments = array_map(function ($key) {
32+
return str_replace('\.', '.', $key);
33+
}, $segments);
3034

3135
return _array_search_dot($segments, $array);
3236
}

tests/system/Helpers/ArrayHelperTest.php

Lines changed: 15 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,21 @@ public function testArrayDotTooManyLevels()
3434
$this->assertEquals(23, dot_array_search('foo.bar.baz', $data));
3535
}
3636

37+
public function testArrayDotEscape()
38+
{
39+
$data = [
40+
'foo' => [
41+
'bar.baz' => 23,
42+
],
43+
'foo.bar' => [
44+
'baz' => 42,
45+
],
46+
];
47+
48+
$this->assertEquals(23, dot_array_search('foo.bar\.baz', $data));
49+
$this->assertEquals(42, dot_array_search('foo\.bar.baz', $data));
50+
}
51+
3752
public function testArrayDotReturnNullEmptyArray()
3853
{
3954
$data = [];

user_guide_src/source/helpers/array_helper.rst

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -57,6 +57,23 @@ The following functions are available:
5757
// Returns: 23
5858
$baz = dot_array_search('foo.*.baz', $data);
5959

60+
If the array key contains a dot, then the key can be escaped with a backslash::
61+
$data = [
62+
'foo' => [
63+
'bar.baz' => 23
64+
],
65+
'foo.bar' => [
66+
'baz' => 43
67+
],
68+
69+
];
70+
71+
// Returns: 23
72+
$barBaz = dot_array_search('foo.bar\.baz', $data);
73+
// Returns: 42
74+
$fooBar = dot_array_search('foo\.bar.baz', $data);
75+
76+
6077
.. php:function:: array_deep_search($key, array $array)
6178
6279
:param mixed $key: The target key

0 commit comments

Comments
 (0)