Skip to content

Lugat/Shortcode-Parser

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

12 Commits
 
 
 
 
 
 

Repository files navigation

Shortcode-Parser

Simple wordpress-like shortcode parser for PHP. Also parses nested shortcodes logically.

Empty shortcodes

Empty shortcodes can be written in both ways: [tag] or [tag /]

  Shortcode::register('week', function($attr, $content) {

    return intval(date('W'));

  });
  
  $input = 'Week in this year: [week]';
    
  echo Shortcode::process($input);

Output

Week in this year: 42

Simple shortcodes

  Shortcode::register('b', function($attr, $content) {

    return '<strong>'.$content.'</strong>';

  });
  
  $input = 'This text is [b]fat[/b]!';
    
  echo Shortcode::process($input);

Output

This text is fat!

Shortcodes with attributes

  
  Shortcode::register('time', function($attr, $content) {
    
    $attr = array_replace([
      'format' => 'H:i:s'
    ], $attr);
    
    return date($attr['format']);
    
  });
  
  $input = 'It\'s [time format="g" /] o\'clock!';
    
  echo Shortcode::process($input);

Output

It's 12 o'clock!

Nested shortcodes

  Shortcode::register('row', function($attr, $content) {
    
    return '<div class="row">'.$content.'</div>';
    
  });
  
  Shortcode::register('col', function($attr, $content) {
    
    $attr = array_replace([
      'width' => 12
    ], $attr);
    
    return '<div class="col-sm-'.$attr['width'].'">'.$content.'</div>';
    
  });
  
  $input = ''
  . '[row]'
    . '[col width="9"]Col 1'
      . '[row]'
        . '[col width="6"]Col 1.1[/col]'
        . '[col width="6"]Col 1.2[/col]'
      . '[/row]'
    . '[/col]'
   . '[col width="3"]Col 2[/col]'
  . '[/row]';
  
  echo Shortcode::process($input);

Output

<div class="row">
  <div class="col-sm-9">Col 1
    <div class="row">
      <div class="col-sm-6">Col 1.1</div>
      <div class="col-sm-6">Col 1.2</div>
    </div>
  </div>
  <div class="col-sm-3">Col 2</div>
</div>

About

Simple wordpress-like shortcode parser for PHP

Topics

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages