-
Notifications
You must be signed in to change notification settings - Fork 0
/
simple-text-editor.php
39 lines (36 loc) · 983 Bytes
/
simple-text-editor.php
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
<?php
$_fp = fopen("php://stdin", "r");
$t = intval(trim(fgets($_fp)));
$queue = [];
$string = '';
for ($x = 0; $x < $t; $x++) {
$line = trim(fgets($_fp));
$parts = explode(' ', $line);
$operation = intval($parts[0]);
switch ($operation) {
case 1:
$string .= $parts[1];
$queue[] = [1, $parts[1]];
break;
case 2:
$length = intval($parts[1]);
$part = substr($string, -$length);
$queue[] = [2, $part];
$string = substr($string, 0, -$length);
break;
case 4:
$op = array_pop($queue);
if (!$op) {
break;
}
if ($op[0] == 1) {
$string = substr($string, 0, -strlen($op[1]));
} else {
$string .= $op[1];
}
break;
default:
$val = intval($parts[1]) - 1;
echo $string[$val] . PHP_EOL;
}
}