1: 2: 3: 4: 5: 6: 7: 8: 9: 10: 11: 12: 13: 14: 15: 16: 17: 18: 19: 20: 21: 22: 23: 24: 25: 26: 27: 28: 29: 30: 31: 32: 33: 34: 35: 36: 37: 38: 39: 40: 41: 42: 43: 44: 45: 46: 47: 48: 49: 50: 51: 52: 53: 54: 55: 56: 57: 58: 59: 60: 61: 62: 63: 64: 65: 66: 67: 68: 69: 70: 71: 72: 73: 74: 75: 76: 77: 78: 79: 80: 81: 82: 83: 84: 85: 86: 87: 88: 89: 90: 91: 92: 93: 94: 95:
<?php
class ShortcodeUtil {
public static function strposAny($subject, $tokens) {
$len=strlen($subject);
for ($i=0; $i<strlen($tokens); $i++) {
$p=strpos($subject,$tokens[$i]);
if ($p!==FALSE && $p<$len)
$len=$p;
}
return $len;
}
public static function tokenize($text) {
$tokens=array();
$text=trim($text);
while (strlen($text)) {
$text=trim($text);
switch ($text[0]) {
case "[":
case "]":
case "=":
$tokens[]=$text[0];
$text=substr($text,1);
break;
case "'":
case '"':
$p=ShortcodeUtil::strposAny(substr($text,1),"\"'");
$tokens[]=substr($text,1,$p);
$text=substr($text,$p+2);
break;
default:
$p=ShortcodeUtil::strposAny($text," \n\t\"'[]=");
$tokens[]=substr($text,0,$p);
$text=substr($text,$p);
break;
}
}
return $tokens;
}
public static function extractShortcodes($text) {
$res=array();
preg_match_all("(\[.*?\])",$text,$matches);
foreach ($matches[0] as $match) {
$tokens=ShortcodeUtil::tokenize($match);
if ($tokens[0]!="[")
throw new Exception("shortcode parse error");
if ($tokens[sizeof($tokens)-1]!="]")
throw new Exception("shortcode parse error");
$tokens=array_slice($tokens,1,sizeof($tokens)-2);
$attr=array();
$attr["_"]=$tokens[0];
$tokens=array_slice($tokens,1);
$i=0;
while ($i<sizeof($tokens)) {
if ($tokens[$i+1]=="=") {
$attr[$tokens[$i]]=$tokens[$i+2];
$i+=3;
}
else {
$attr[$tokens[$i]]=TRUE;
$i++;
}
}
$res[]=$attr;
}
return $res;
}
}