-
Notifications
You must be signed in to change notification settings - Fork 4
Expand file tree
/
Copy pathMyCode.php
More file actions
91 lines (78 loc) · 1.87 KB
/
Copy pathMyCode.php
File metadata and controls
91 lines (78 loc) · 1.87 KB
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
<?php
$template = '[_B][_I]foo[/I][/B]';
$tags['_B'] = '<b>[_*]</b>';
$tags['_I'] = '<i>[_*]</i>';
$parser = new MyCode();
$tokens = $parser->tokenize($template);
echo $parser->parse($tokens, $tags);
class Token {
public $content;
public $type;
}
class MyCode {
public function parse($tokens) {
$content = '';
$stack = array();
foreach($tokens as $token) {
switch($token->type) {
case 'tag':
$stack[] = array(
'callback' => function($input) use($tags, $token) { return str_replace('[_*]', $input, $tags[$token->content]); },
'content' => ''
);
break;
case 'end_tag':
$instruction = array_pop($stack);
$func = $instruction['callback'];
$content .= $func($instruction['content']);
break;
default:
if($stack) {
$instruction = array_pop($stack);
$instruction['content'] .= $token->content;
$stack[] = $instruction;
} else {
$content .= $instruction['content'];
}
break;
}
}
return $content;
}
public function tokenize($code) {
$index = 0;
$tokens = array();
$len = strlen($code);
while($index < $len) {
if(substr($code, $index, 2) == '[_') {
$token = new Token();
$token->type = 'tag';
$index += 2;
$startindex = $index;
while(true) {
if($code[$index] == ']') {
$token->content = substr($code, $startindex, $index - $startindex);
}
if($index == $len) {
throw new Exception('Unterminated [_..] tag');
}
}
$tokens[] = $token;
} else {
$startindex = $index;
while($index < $len) {
if(substr($code, $index, 2) == '[_') {
$index--;
$token = new Token();
$token->type = 'content';
$token->content = substr($code, $startindex, $index - $startindex);
$tokens[] = $token;
continue 2;
}
$index++;
}
}
}
return $tokens;
}
}