Skip to content

Commit

Permalink
Fix bug with shortcodes having matching prefixes (#11)
Browse files Browse the repository at this point in the history
Solve by first sorting from longest to shortest, so the regex
alternation matches the most specific first.
  • Loading branch information
samwilson authored Apr 12, 2024
1 parent 0899b75 commit 944474e
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 3 deletions.
8 changes: 7 additions & 1 deletion src/ShortcodeInlineParser.php
Original file line number Diff line number Diff line change
Expand Up @@ -23,9 +23,15 @@ public function __construct(array $shortcodes)

public function getMatchDefinition(): InlineParserMatch
{
// Sort shortcodes by length, so they match from longest to shortest in the regex.
$sortedShortcodeNames = \array_keys($this->shortcodes);
\usort($sortedShortcodeNames, static function ($a, $b) {
return \strlen($b) - \strlen($a);
});

return InlineParserMatch::join(
InlineParserMatch::string('{'),
InlineParserMatch::oneOf(...\array_keys($this->shortcodes)),
InlineParserMatch::oneOf(...$sortedShortcodeNames),
InlineParserMatch::regex('.*?'),
InlineParserMatch::string('}')
);
Expand Down
4 changes: 2 additions & 2 deletions tests/ShortcodeExtensionTest.php
Original file line number Diff line number Diff line change
Expand Up @@ -34,12 +34,12 @@ public function provideBasics(): array
{
return [
'simple-inline' => [
'markdown' => 'Foo {bar} baz {bif}',
'markdown' => 'Foo {bar} baz {barbif}',
'shortcodes' => [
'bar' => static function () {
return 'BAR';
},
'bif' => static function () {
'barbif' => static function () {
return 'BIF';
},
],
Expand Down

0 comments on commit 944474e

Please sign in to comment.