Download the PHP package thunderer/shortcode without Composer
On this page you can find all versions of the php package thunderer/shortcode. It is possible to download/install these versions without Composer. Possible dependencies are resolved automatically.
Informations about the package shortcode
Shortcode
Shortcode is a framework agnostic PHP library allowing to find, extract and process text fragments called "shortcodes" or "BBCodes". Examples of their usual syntax and usage are shown below:
The library is divided into several parts, each of them containing logic responsible for different stages and ways of processing data:
- parsers extract shortcodes from text and transform them to objects,
- handlers transform shortcodes into desired replacements,
- processors use parsers and handlers to extract shortcodes, compute replacements, and apply them in text,
- events alter the way processors work to provide better control over the whole process,
- serializers convert shortcodes from and to different formats like Text, XML, JSON, and YAML.
Each part is described in the dedicated section in this document.
Installation
There are no required dependencies and all PHP versions from 5.3 up to latest 8.x are tested and supported. This library is available on Composer/Packagist as thunderer/shortcode
, to install it execute:
or manually update your composer.json
with:
and run composer install
or composer update
afterwards. If you're not using Composer, download sources from GitHub and load them as required. But really, please use Composer.
Usage
Facade
To ease usage of this library there is a class ShortcodeFacade
configured for most common needs. It contains shortcut methods for all features described in the sections below:
addHandler()
: adds shortcode handlers,addHandlerAlias()
: adds shortcode handler alias,process()
: processes text and replaces shortcodes,parse()
: parses text into shortcodes,setParser()
: changes processor's parser,addEventHandler()
: adds event handler,serialize()
: serializes shortcode object to given format,unserialize()
: creates shortcode object from serialized input.
Processing
Shortcodes are processed using Processor
which requires a parser and handlers. The example below shows how to implement an example that greets the person with name passed as an argument:
Facade example:
Both result in:
Configuration
Processor
has several configuration options available as with*()
methods which return the new, changed instance to keep the object immutable.
withRecursionDepth($depth)
controls the nesting level - how many levels of shortcodes are actually processed. If this limit is reached, all shortcodes deeper than level are ignored. If the$depth
value is null (default value), nesting level is not checked, if it's zero then nesting is disabled (only topmost shortcodes are processed). Any integer greater than zero sets the nesting level limit,withMaxIterations($iterations)
controls the number of iterations that the source text is processed in. This means that source text is processed internally that number of times until the limit was reached or there are no shortcodes left. If the$iterations
parameter value is null, there is no iterations limit, any integer greater than zero sets the limit. Defaults to one iteration,withAutoProcessContent($flag)
controls automatic processing of shortcode's content before calling its handler. If the$flag
parameter istrue
then handler receives shortcode with already processed content, iffalse
then handler must process nested shortcodes itself (or leave them for the remaining iterations). This is turned on by default,withEventContainer($events)
registers event container which provides handlers for all the events fired at various stages of processing text. Read more about events in the section dedicated to them.
Events
If processor was configured with events container there are several possibilities to alter the way shortcodes are processed:
Events::FILTER_SHORTCODES
usesFilterShortcodesEvent
class. It receives current parent shortcode and array of shortcodes from parser. Its purpose is to allow modifying that array before processing them,Events::REPLACE_SHORTCODES
usesReplaceShortcodesEvent
class and receives the parent shortcode, currently processed text, and array of replacements. It can alter the way shortcodes handlers results are applied to the source text. If none of the listeners set the result, the default method is used.
There are several ready to use event handlers in the Thunder\Shortcode\EventHandler
namespace:
FilterRawEventHandler
implementsFilterShortcodesEvent
and allows to implement any number of "raw" shortcodes whose content is not processed,ReplaceJoinEventHandler
implementsReplaceShortcodesEvent
and provides the mechanism to apply shortcode replacements by discarding text and returning just replacements.
The example below shows how to manually implement a [raw]
shortcode that returns its verbatim content without calling any handler for nested shortcodes:
Facade example:
Parsing
This section discusses available shortcode parsers. Regardless of the parser that you will choose, remember that:
- shortcode names can be only aplhanumeric characters and dash
-
, basically must conform to the[a-zA-Z0-9-]+
regular expression, - unsupported shortcodes (no registered handler or default handler) will be ignored and left as they are,
- mismatching closing shortcode (
[code]content[/codex]
) will be ignored, opening tag will be interpreted as self-closing shortcode, eg.[code /]
, - overlapping shortcodes (
[code]content[inner][/code]content[/inner]
) will be interpreted as self-closing, eg.[code]content[inner /][/code]
, second closing tag will be ignored,
There are three included parsers in this library:
RegularParser
is the most powerful and correct parser available in this library. It contains the actual parser designed to handle all the issues with shortcodes like proper nesting or detecting invalid shortcode syntax. It is slightly slower than regex-based parser described below,RegexParser
uses a handcrafted regular expression dedicated to handle shortcode syntax as much as regex engine allows. It is fastest among the parsers included in this library, but it can't handle nesting properly, which means that nested shortcodes with the same name are also considered overlapping - (assume that shortcode[c]
returns its content) string[c]x[c]y[/c]z[/c]
will be interpreted asxyz[/c]
(first closing tag was matched to first opening tag). This can be solved by aliasing handler name, because for example[c]x[d]y[/d]z[/c]
will be processed correctly,WordpressParser
contains code copied from the latest currently available WordPress (4.3.1). It is also a regex-based parser, but the included regular expression is quite weak, it for example won't support BBCode syntax ([name="param" /]
). This parser by default supports the shortcode name rule, but can break it when created with one of the named constructors (createFromHandlers()
orcreateFromNames()
) that change its behavior to catch only configured names. All of it is intentional to keep the compatibility with what WordPress is capable of if you need that compatibility.
Syntax
All parsers (except WordpressParser
) support configurable shortcode syntax which can be configured by passing SyntaxInterface
object as the first parameter. There is a convenience class CommonSyntax
that contains default syntax. Usage is shown in the examples below:
Default syntax (called "common" in this library):
Syntax with doubled tokens:
Something entirely different just to show the possibilities:
Verify that each syntax works properly:
Serialization
This library supports several (un)serialization formats - XML, YAML, JSON and Text. Examples below shows how to both serialize and unserialize the same shortcode in each format:
Text:
JSON:
YAML:
XML:
Facade also supports serialization in all available formats:
Handlers
There are several builtin shortcode handlers available in Thunder\Shortcode\Handler
namespace. Description below assumes that given handler was registered with xyz
name:
NameHandler
always returns shortcode's name.[xyz arg=val]content[/xyz]
becomesxyz
,ContentHandler
always returns shortcode's content. It discards its opening and closing tag.[xyz]code[/xyz]
becomescode
,RawHandler
returns unprocessed shortcode content. Its behavior is different thanFilterRawEventHandler
because if content auto processing is turned on, then nested shortcodes handlers were called, just their result was discarded,NullHandler
completely removes shortcode with all nested shortcodes,DeclareHandler
allows to dynamically create shortcode handler with name as first parameter that will also replace all placeholders in text passed as arguments. Example:[declare xyz]Your age is %age%.[/declare]
created handler for shortcodexyz
and when used like[xyz age=18]
the result isYour age is 18.
,EmailHandler
replaces the email address or shortcode content as clickablemailto:
link:[xyz="[email protected]" /]
becomes<a href="[email protected]">[email protected]</a>
,[xyz][email protected][/xyz]
becomes<a href="[email protected]">[email protected]</a>
,[xyz="[email protected]"]Contact me![/xyz]
becomes<a href="[email protected]">Contact me!</a>
,
PlaceholderHandler
replaces all placeholders in shortcode's content with values of passed arguments.[xyz year=1970]News from year %year%.[/xyz]
becomesNews from year 1970.
,SerializerHandler
replaces shortcode with its serialized value using serializer passed as an argument in class' constructor. If configured withJsonSerializer
,[xyz /]
becomes{"name":"json", "arguments": [], "content": null, "bbCode": null}
. This could be useful for debugging your shortcodes,UrlHandler
replaces its content with a clickable link:[xyz]http://example.com[/xyz]
becomes<a href="http://example.com">http://example.com</a>
,[xyz="http://example.com"]Visit my site![/xyz]
becomes<a href="http://example.com">Visit my site!</a>
,
WrapHandler
allows to specify the value that should be placed before and after shortcode content. If configured with<strong>
and</strong>
, the text[xyz]Bold text.[/xyz]
becomes<strong>Bold text.</strong>
.
Contributing
Want to contribute? Perfect! Submit an issue or Pull Request and explain what would you like to see in this library.
License
See LICENSE file in the main directory of this library.