BBcode Parser + Highlighter

Door Richard van Velzen, 23 jaar geleden, 9.564x bekeken

Ik werd het zwaar zat om steeds regex-based bbcode 'parsers' te zien, die niet bepaald soepel waren, en moeilijk uit te breiden voor beginners.
Met deze class hoop ik hier verandering in te kunnen brengen door het stackbased te parsen.

Deze class parsed eerst alles in delen, waarbij het bijvoorbeeld eerst een tag, dan tekst, dan weer tags in een array komen te staan, waarna het script erdoorheen lust, en op die manier het parsen van bbcode binnen bepaalde tags ZEER simpel kan maken. Op deze manier heb ik er ook voor gezorgd dat je code tags kunt nesten, zodat als je [.code.] en [./code.] binnen je code hebt staan, hij niet direct bij de 2e sluit.

Voor meer informatie over gebruik, zie de readme in de zip (het zijn te veel bestanden om hier te posten - vooral te veel data).


UPDATE 1.1: js en css nu in de zip toegevoegd, readme uitgebreid, en wat bugs eruit gesloopt;)

Gesponsorde koppelingen

PHP script bestanden

  1. bbcode-parser-highlighter

 

Er zijn 33 reacties op 'Bbcode parser highlighter'

PHP hulp
PHP hulp
0 seconden vanaf nu
 

Gesponsorde koppelingen
Pieter van Linschoten
Pieter van Linschoten
23 jaar geleden
 
0 +1 -0 -1
Beetje veel commentaar tussen de code om een snel overzicht te krijgen, maar 't ziet er goed uit :D
Willem Jan Z
Willem Jan Z
23 jaar geleden
 
0 +1 -0 -1
Ik denk dat dat ignore nog best van past kan komen af en toe :)


23 jaar geleden
 
0 +1 -0 -1
ziet er erg goed uit...
het zijn precies de codes van PHPhulp, maar die bevallen me wel hoor:p
Dutchcamel
dutchcamel
23 jaar geleden
 
0 +1 -0 -1
Ziet er idd heel netjes uit! Ik was zelf net van plan zoiets te gaan schrijven, maar aan de code te zien was dat toch niet zo eenvoudig geweest als ik eigenlijk dacht :) Je methode heet trouwens een stack-based parser, dat is misschien wel handig om erbij te zetten in de toelichting.
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
LOL, helemaal vergeten:P in het nieuwsbericht waardoor ik de aanleiding kreeg om het hier te posten stond het overigens wel:P
Lissy Pixel
Lissy Pixel
23 jaar geleden
 
0 +1 -0 -1
Bedankt voor het delen en met name dat dit ook leesbaar is voor beginners :)
Fijn dat je dit met ons wil delen!!!
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
Tja, iedereen heeft profijt van een ECHTE parser, die nog veel meer functionaliteit heeft ook;)
Jorik
Jorik
23 jaar geleden
 
0 +1 -0 -1
Enige wat ik mis zijn smilies, zoek nu even uit hoe moeilijk het is ze toe te voegen. Ziet er overigens erg netjes uit, vooral de code highlight.
Dat de preg_replace dingen veel gebruikt worden, is niet zo moeiljik te verklaren overigens. Het werkt gewoon zoals de bedoeling is, het zal [.b.] test niet doen, maar [.b.] test [./b.] wél., gewono veiliger. Weet niet hoe he tmet jou script zit, dat ga ik nu even proberen ;).

Even testen, werkt allemaal vrij netjes. het [.b.] verhaal werkt echt zeer soepel, als ik start, zet ie aan het einde gewono [./b.] neer.
Helaas ben ik neit zo te spreken van de standaard layout, en (nieuw venster) werkt ook niet in FF & IE, JS error:
Fout open_content is not defined
Bronbestand javascript:open_content('field_1', 400, 400);
Regel 1

Ik heb even jouw bron gekopieërd (CSS& JS) en het werkt nu véle malen mooier. Misschien een idee dit erbij te vermelden (heb ik wat gemist misschien ?)

Functies in een nieuw venster is misschien een idee? (of ivb met XHTML Strict niet..?)

Code in venster vindt ik opzich ook een hele leuke optie (code downloaden is ook leuk), alleen jammergenoeg vult het me hele scherm? Mooier zou een kleiner schermpje zijn.
Dutchcamel
dutchcamel
23 jaar geleden
 
0 +1 -0 -1
Als ik dan even voor Richard mag antwoorden; dat alleen [.b] niet werkt doet deze uiteraard ook, en nog beter ook. Hiermee zijn ook veel beter geneste tags af te handelen. Doordat het stack-based is wordt meteen gecontroleerd of alles wat geopend wordt ook (op het goede moment) weer gesloten wordt. Smileys en BB-codes zijn niet hetzelfde, vandaar dat Richard die hier niet bij heeft zitten natuurlijk.

@Richard, als ik wat verkeerd zeg corrigeer me maar :)


23 jaar geleden
 
0 +1 -0 -1
Dat geneste is wel goed! Zeker bij XHTML.
Jorik
Jorik
23 jaar geleden
 
0 +1 -0 -1
Warning: Call-time pass-by-reference has been deprecated - argument passed by value; If you would like to pass it by reference, modify the declaration of method_exists(). If you would like to enable call-time pass-by-reference, you can set allow_call_time_pass_reference to true in your INI file. However, future versions may not support this any longer. in C:\Webserver\www\ubb\text_parser.class.php on line 378

Werkt niet helemaal lekker...
('t is maar een warning, maar toch)
Overigens: Apache/2.0.55 (Win32) PHP/5.0.5 Server at localhost Port 80
Martijn B
Martijn B
23 jaar geleden
 
0 +1 -0 -1
De code ziet er goed uit mooi script. Alleen nog een in en uitklap functie in Javascript voor de kader breedtes en dit script kan op phphulp.

Quote:
Warning: Call-time pass-by-reference has been deprecated ... in C:\Webserver\www\ubb\text_parser.class.php on line 378

Volgens mij kun je gewoon regel 378 vervangen door:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
<?php

&& method_exists ($this, '_parse_bb_' . $name)

?>


Er wordt gecontroleerd of een bepaalde methode bestaat in het huidige object, waarom je dan het object als referencie meegeeft is mij een raadsel.
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
Bedankt voor de reacties en opmerkingen! ik ga meteen de code wijzigen, en opnieuw zippen plus uploaden;)
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
De download is geupdate. Ik heb de readme flink uitgebreid, met uitleg hoe je nieuwe tags en bijvoorbeeld smilies kunt toevoegen. Ook zitten de javascript en css nu bij de zip in.
Martijn B
Martijn B
23 jaar geleden
 
0 +1 -0 -1
Ik heb een in en uitklap functie
in Javascript gemaakt voor de code tags:

http://fairplayweb.nl/martijn/bb/

Getest op: Firefox 1.5.0.1 en IE 6.0

Zo en nu even installeren op phphulp ;D
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
Het spijt me het te zeggen, maar hier werkt t niet;) IE 6
Martijn B
Martijn B
23 jaar geleden
 
0 +1 -0 -1
Hier dus wel, zie je de pijltjes wel?

Zo niet, dan staat Javascript uit waarschijnlijk.
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
Ik zie alles, maar als ik op de pijltjes klik word de tabel vervormd zodat de code erin past, meer gebeurt niet;) maar ik heb zelf wel een scriptje dat ik erin zal bouwen.
Jorik
Jorik
23 jaar geleden
 
0 +1 -0 -1
Ehm.. dat is toch ook de bedoeling? Dan kun je nl. het hele script zien zonder te scrollen ;).
Overigens zou het mooi zijn (weet niet of het mogelijk is) om de scrollbar alleen te tonen wanneer nodig, bij het voorbeeld de 2e zou het niet nodig zijn. Weet niet of het mogelijk is..
Richard van Velzen
Richard van Velzen
23 jaar geleden
 
0 +1 -0 -1
inklap != alles laten zien, maar het code gedeelte verbergen;) daar zijn nog wel iets meer aanpassingen voor nodig. komt in de volgende release!
Erik
Erik
22 jaar geleden
 
0 +1 -0 -1
Is het mogelijk om je code te ZIPPEN, het ZIP scriptje heb ik namelijk wel maar het lukt mij niet om op eenvoudige wijze de code in te pakken in een tekstbestand en deze te laten zippen...
Richard van Velzen
Richard van Velzen
22 jaar geleden
 
0 +1 -0 -1
Wat bedoel je daarmee?

code uit code blokken?
Erik
Erik
22 jaar geleden
 
0 +1 -0 -1
Ja inderdaad, de code die je ziet als highlighted code. Die code wil ik inpakken in een ZIP-bestand door de code in een tekstbestand te schrijven en dat vervolgens met een linkje direct te laten ZIPPEN en dat je gelijk het downloadvenster krijgt.
Richard van Velzen
Richard van Velzen
22 jaar geleden
 
0 +1 -0 -1
Ik ben eerst bezig de code te herschrijven (ik ga alles in andere bestanden zetten etc.), daarna zal ik deze (eenvoudige;)) optie inbouwen.
Erik
Erik
22 jaar geleden
 
0 +1 -0 -1
Hahaha... eenvoudige zegt ie dan, nou ik puzzle dan nog wel even verder (iets wat ik nu al een hele dag doe)... ben nog niets opgeschoten
Richard van Velzen
Richard van Velzen
22 jaar geleden
 
0 +1 -0 -1
Het is in principe heel simpel;) Je maakt een nieuwe class member aan, bijvoorbeeld _code_blocks, in de _parse_bb_code method laat je ieder geparsed block opslaan in de _code_blocks (of natuurlijk de niet gehighlighte code), die kun je met een nieuwe method uitlezen;) makkie eigelijk.
Frank
Frank
22 jaar geleden
 
0 +1 -0 -1
Ik heb een klein stukje code toegevoegd om te checken of het wel echt een plaatje is wat men invoegt!

Code (php)
PHP script in nieuw venster Selecteer het PHP script
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
<?php
$known_img_ext
= array( 'jpg','gif','jpeg','png');
        
// we only want img with ext. wich are in the $known_img_ext array so we get the ext. and check if the ext. is allowed
$ext = substr (strrchr ($img, "."), 1);
            
// go back into bb_mode
$this->_bb_mode = true;
        
if( in_array ($ext, $known_img_ext) AND !ereg('\?', $img) AND !ereg('\&', $img) ) { // if ext. is allowed
            
// get some basic arguments

$width          = (isset ($args['width'])) ? $args['width'] : 0;
$height         = (isset ($args['height'])) ? $args['height'] : 0;
$alt            = (isset ($args['alt'])) ? $args['alt'] : '';

// create the return statement
$return  = '<img src="' . $img . '"';
$return .= ($width) ? ' width="' . $width . '"' : '';
$return .= ($height) ? ' height="' . $height . '"' : '';
$return .= ($alt) ? ' alt="' . $alt . '"' : '';
$return .= ' />';
}

else {
            $return = "<div style='border: 1px solid red; background-color: #D3D3D3;'><div style='border: 1px solid red; border-bottom: 2px solid red; background-color: #FF8040; padding-left: 5px; padding-right: 5px; text-color: red; font-weight: bold;'>IMG ERROR:</div><div style='padding: 5px;'>";
            if( ereg('\&', $img) )
                $return .= "Sorry, er mag geen & teken in de bestandsnaam voorkomen!<br />";
            if( ereg('\?', $img) )
                $return .= "Sorry, er mag geen ? teken in de bestandsnaam voorkomen!<br />";
            if( !in_array($ext, $known_img_ext) )
                $return .= "Sorry, deze extentie (".$ext.") is niet toegestaan!<br />";
            $return .= "</div></div>";
}

?>


dit moet onder
Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
<?php
// get the url
$img            = (isset ($args['img']))
            ?
$args['img']
            :
$this->_parse ('[/img]');
?>


komen te staan in het bestand "text_parser.class.php" in plaats van het stukje code wat hieronder staat in de functie _parse_bb_img

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
<?php
// go back into bb_mode
$this->_bb_mode = true;

// get some basic arguments
$width          = (isset ($args['width'])) ? $args['width'] : 0;
$height         = (isset ($args['height'])) ? $args['height'] : 0;
$alt            = (isset ($args['alt'])) ? $args['alt'] : '';

// create the return statement
$return  = '<img src="' . $img . '"';
$return .= ($width) ? ' width="' . $width . '"' : '';
$return .= ($height) ? ' height="' . $height . '"' : '';
$return .= ($alt) ? ' alt="' . $alt . '"' : 'Plaatje';
$return .= ' />';
?>


voor de mensen die dit beetje lastige beschrijving vinden heb ik hier nog even de hele file text_parser.class.php

Code (php)
PHP script in nieuw venster Selecteer het PHP script
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
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
<?php
/**
 * Text Parsing functions
 * This class parses bbcode in a given text to html,
 * but not in the way you'd expect. It creates an array
 * in which all possible tags and text is stored, and
 * it loops through, searching for correct tags, and
 * attaches them to a new-built string. This way is
 * much faster and more reliable than usual preg/ereg
 * based parsers, and has taken quite a while;)
 * It also includes the highlighthing class for the
 * <b>Quality Bulletin Board</b>. It is very flexible,
 * and works with language files, which are on
 * their turn based on regular expressions.
 * This makes it all very flexible, and easy to edit.
 *
 * @author       JeXuS <[email protected]>
 * @package      TP
 * @filesource
 * @version      0.95b
 * @date         12-02-2006
**/
// full error reporting

error_reporting (E_ALL);

/**
 * This constant means that a regular expression
 * does not need any modifiers.
 *
 * @name   QBB_NONE
**/

define ('QBB_NONE', 0);
/**
 * This constant means that a regular expression
 * needs the '.' to match newlines too.
 *
 * @name   QBB_DOTALL
**/

define ('QBB_DOTALL', 1);
/**
 * This constant means that a regular expression
 * has to match without case-sensitivity.
 *
 * @name   QBB_CASELESS
**/

define ('QBB_CASELESS', 2);


/**
 * Parse text to bbcode using stacks
 *
 * @author      JeXuS   <[email protected]>
 * @copyright   (c) 2005-2005 JeXuS.net
 * @package     TP
 *
 * @todo        add smiley support
 * @todo        check if XSS protection is secure
**/

class bbcode
{
    /**#@+
    * @access   protected
    */

    /**
    * Contains parsed text
    *
    * @var      array     _parsed
    **/

    var $_parsed = array ();
    /**
    * Contains aliases
    *
    * @var      array     _alias
    **/

    var $_alias = array (
        '*' => 'li_short',
        'hr' => 'line'
    );
    /**
    * Parse tags?
    *
    * @var      boolean   _bb_mode
    **/

    var $_bb_mode = true;
    /**
    * Holds bbcode templates
    *
    * @var      array     _tpls
    **/

    var $_tpls = array ();
    /**
    * Regexes that'll be used
    *
    * @var      array     _regexes
    **/

    var $_regexes = array ();
    /**
    * All other simple replacement
    *
    * @var      array     _replaces
    **/

    var $_replaces = array ();
    /**
    * Check if we're inside tags
    *
    * Are we parsing inside a tag that's special?
    * extra care taken, because tags
    * may be nested
    *
    * @var      array     _in_tag
    **/

    var $_in_tag = array (
        'list' => 0,
        'table' => 0,
        'tr' => 0
    );
    /**
    * ID for div's
    *
    * @var      integer   _curr_id
    **/

    var $_curr_id = 1;

    /**#@-*/

    /**#@+
    * @access   public
    **/

    /**
    * BBcode parsing constructor
    *
    * Sets up templates, autolinking etc.
    *
    * @param    string   [$tpl_file]
    * @return   boolean
    **/

    function bbcode ($tpl_file = './bbcode_tpl.htm')
    {

        // get the data from the tpl file
        $data = file_get_contents ($tpl_file);
        $data = str_replace ('\\', '\\\\', $data);
        $data = str_replace ("'", "\'", $data);

        // replace all bb parts with a PHP piece which will insert it
        // into the tpl array

        $data = preg_replace (
            '/<!-- BEGIN BB ([^\s]+) -->(.*?)<!-- END BB \1 -->/si',
            "\$this->_tpls['\\1'] = trim ('\\2');",
            $data
        );
        // evaluate
        eval ($data);

        // some action for the replacement of email links etc.
        $this->_regexes = array (
            'find' => array (
                // emails
                '~(\s|^)([-a-z_][-a-z0-9._]*@[-a-z0-9_]+(?:\.[-a-z0-9_]+)+)\b~si',
                // links with http, https, ftp or even irc
                '~(\s|^)((?:https?|ftp|irc)://[-a-z0-9+&@#/%?=\~_|!:,.;]*[-a-z0-9+&@#/%=\~_|])\b~si',
                // links with www.
                '~(\s|^)((?:[a-z][-a-z0-9+&@#/%?=\~_|!:,.;]+)\.(?:[a-z]{2,6}))\b~si'
            ),
            'replace' => array (
                '\1<a href="mailto:\2">\2</a>',
                '\1<a href="\2">\2</a>',
                '\1<a href="http://\2">\2</a>',
            )
        );


        // this can handle anything like smilies.
        $this->_replace = array (
            'find'    => array (),
            'replace' => array ()
        );


        // and return
        return true;
    }


    /**
    * Call this to return a parsed text
    *
    * @param    string   $text
    * @return   string
    **/

    function parse ($text)
    {

        // remove beginning and ending whitespaces
        $text = trim ($text);
        // replace all newlines with a linebreak tag (for later use)
        $text = str_replace (array ("\r\n", "\r", "\n"), "[linebreak\0]", $text);

        // cut the text in pieces so we can easily loop
        $this->_create_array (htmlspecialchars ($text));

        // parse the stack
        $text = $this->_parse ();

        // replace the linebreak tags with normal newlines
        $return = str_replace ("[linebreak\0]", "<br />\n", $text);
        // and return
        return $return;
    }


    /**#@-*/

    /**#@+
     * @access   protected
     **/

    /**
     * Parse a template with given variables
     *
     * @param    string   $part
     * @param    array    $args
     * @return   string
    **/

    function parse_bb_tpl ($part, $args)
    {

        // just a replace, with evaluation...
        return preg_replace (
            '/{([^}\s]+)}/e',
            "isset (\$args['\\1']) ? \$args['\\1'] : '';",
            $this->_tpls[$part]
        );
    }


    /**
     * Cut the text in pieces
     *
     * @param    string   $text
     * @return   boolean
    **/

    function _create_array ($text)
    {

        // empty the _parsed array
        $this->_parsed = array ();

        // loop as long as the text has content
        while (strlen ($text) > 0)
        {

            // the first found bracket
            $bracket        = strpos ($text, '[');
            // the second bracket
            $second_bracket = strpos ($text, '[', $bracket + 1);
            // and the first closer
            $close          = strpos ($text, ']');

            // if there isnt a bracket or closer
            if ($bracket === false || $close === false)
            {

                // the rest is just normal text
                $this->_parsed[] = $text;
                // return
                return true;
            }


            // loop as long as the [ and ] aren't right
            while ($close < $bracket || $second_bracket < $close)
            {

                // look if the second bracket comes before the closer
                if ($second_bracket < $close)
                {

                    // if so, $bracket gets the value of $second_bracket
                    $bracket = $second_bracket;
                    // the second bracket gets a new position
                    $second_bracket = strpos ($text, '[', $bracket + 1);
                    // if that wasn't matched right
                    if (!$second_bracket)
                    {

                        // the second bracket will be matched after the closer
                        $second_bracket = $close + 1;
                    }
                }

                // if the closer comes before the [
                if ($close < $bracket)
                {

                    // update the closer
                    $close = strpos ($text, ']', $close + 1);
                }
            }


            // if the [ and ] seem to be correct
            if ($bracket < $close && $close < $second_bracket)
            {

                // the text before the tag
                $pre = substr ($text, 0, $bracket);
                // if this is empty
                if (strlen ($pre) > 0)
                {

                    // add this to the _parsed
                    $this->_parsed[] = $pre;
                    // memory saving
                    $pre = '';
                }

                // put the text in _parsed
                $this->_parsed[] = substr ($text, $bracket, $close - $bracket + 1);
                // $text has to be updated
                $text            = substr ($text, $close + 1);
            }
        }

        // return
        return true;
    }


    /**
     * Parse the text (already cut in pieces)
     *
     * @param    array   [$stoppers]
     * @param    array   [$allow]
     * @return   string
    **/

    function _parse ($stoppers = array (), $allow = array ())
    {

        // if the stack is empty
        if (!$this->_parsed)
        {

            // return nothing
            return '';
        }


        // nested level and return text ''
        $level = 0;
        $text = '';

        // simple check so we can easily check
        if (!is_array ($stoppers))
        {

            $stoppers = array ($stoppers);
        }


        // for even levels with bb_mode off
        $stoppers_leveled = array ();
        // check for active bb_mode
        if (!$this->_bb_mode)
        {

            // if it isn't active, we put all the stoppers in an array
            // so we can check for the correct level

            for ($i = 0, $size = count ($stoppers); $i < $size; $i++)
            {

                // use the tagname function
                $stoppers_leveled[$this->_find_tagname ($stoppers[$i], false, true)] = true;
            }
        }

        // flip the stoppers so we can use isset
        $stoppers = array_flip ($stoppers);
        $allow    = array_flip ($allow);

        // loop the pieces
        while ($piece = array_shift ($this->_parsed))
        {

            // if it is a stopper
            if (isset ($stoppers[$piece]))
            {

                // check for zero-level or bb_mode active
                if (($level == 0 && !$this->_bb_mode) || $this->_bb_mode)
                {

                    // if correct, return
                    return $text;
                }

                // otherwise...
                else
                {
                    // attach this piece
                    $text .= $piece;
                    // and lower the level
                    $level--;
                }
            }

            // if it isn't a stopper
            else
            {
                // check if we can find a tagname first
                $name = $this->_find_tagname ($piece);
                $name = ($name !== false && isset ($this->_alias[$name]))
                    ?
$this->_alias[$name]
                    :
$name;

                $allowed = (isset ($allow[$name]) || !$allow) ? true : false;

                // if it was a valid tag, and the correct method exists
                if ($name !== false
                    && method_exists (&$this, '_parse_bb_' . $name)
                    &&
$allowed === true)
                {

                    // check if bb_mode is active
                    if ($this->_bb_mode)
                    {

                        // if so, find the complete tag without []
                        $args     = $this->_find_tagname ($piece, true);
                        // parse the arguments
                        $args     = $this->_parse_bb_arguments ($args);
                        // the correct method
                        $function = '_parse_bb_' . $name;
                        // append the parsed text to the text
                        $text    .= $this->$function ($args);
                    }

                    // if bb_mode is unactive
                    else
                    {
                        // check if this is a stopper
                        if (isset ($stoppers_leveled[$name]))
                        {

                            // if so, update the level
                            $level++;
                        }

                        // and append
                        $text .= $piece;
                    }
                }

                // if it wasn't a tag
                else
                {
                    // check if we're in a disallowed zone
                    if (!$allow)
                    {

                        // if bb_mode is active
                        if ($this->_bb_mode)
                        {

                            // use the regexes to form a nicer text
                            $piece = preg_replace (
                                $this->_regexes['find'],
                                $this->_regexes['replace'],
                                $piece
                            );
                            $piece = str_replace (
                                $this->_replace['find'],
                                $this->_replace['replace'],
                                $piece
                            );
                        }

                        // just a normal append
                        $text .= $piece;
                    }
                }
            }
        }

        // after the loop just return
        return $text;
    }


    /**
     * find the name of a tag in a piece of the content
     *
     * @param    string    $name
     * @param    boolean   [$complete]
     * @param    boolean   [$closer]
     * @return   string
    **/

    function _find_tagname ($name, $complete = false, $closer = false)
    {

        // check if it could be valid
        if (substr ($name, 0, 1) == '[' && substr ($name, -1) == ']')
        {

            // take off the [ and ]
            $name = substr ($name, 1, -1);
            // if it matches a /
            if (substr ($name, 0, 1) == '/' && $closer !== false)
            {

                // take the / off too
                $name = substr ($name, 1);
            }


            // if it should be the complete tag
            if ($complete !== false)
            {

                // then return it now
                return $name;
            }

            // otherwise use strtok to match untill ' ' or '='
            return strtok ($name, ' =');
        }

        // if it wasn't valid, return boolean false
        return false;
    }


    /**
     * parse argument strings
     *
     * @param    string   $total
     * @return   array
    **/

    function _parse_bb_arguments ($total)
    {

        // instantiate for errors
        $matches = array ();
        // match everything like argument='blablabla bla' or argument=blabla or even arg='bla\'bla\\'bla\\'
        preg_match_all (
            '/([A-Za-z_]+?)=(?:(\'|&quot;)(.*?(?<!\\\\)(?:\\\\\\\\)*)\2|([^\s]+))' .
                '(?:\s|$)/s',
            $total,
            $matches,
            PREG_SET_ORDER
        );

        // put up the arguments array
        $args = array ();
        // loop through all matches
        for ($i = 0, $size = count ($matches); $i < $size; $i++)
        {

            // check if the quoted value was empty
            if (trim ($matches[$i][3]) == '')
            {

                // if the unquoted value was empty
                if (trim ($matches[$i][4]) == '')
                {

                    // the value is ''
                    $value = '';
                }

                // if not
                else
                {
                    // assign the unquoted value
                    $value = $matches[$i][4];
                }
            }

            // otherwise
            else
            {
                // assign the quoted value
                $value = $matches[$i][3];
            }


            // erase whitespaces
            $value = trim ($value);
            // if the value wasn't empty
            if ($value != '')
            {

                // assign this argument to our array
                $args[strtolower ($matches[$i][1])] = $value;
            }
        }


        // return the arguments
        return $args;
    }


    /*
     * THE PARSING FUNCTIONS BEGIN HERE
     * a function should be built like this:
     * name: _parse_bb_*tagname*
     * 1 argument, $args for the given arguments
     * pickup the content with $this->_parse (array ('stoppers1', 'stoppers2'));
     * or with $this->_parse ('stopper');
     * return.
    **/

    /**
     * show bold text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_b ($args)
    {

        return '<b>' . $this->_parse ('[/b]') . '</b>';
    }


    /**
     * show italic text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_i ($args)
    {

        return '<i>' . $this->_parse ('[/i]') . '</i>';
    }


    /**
     * show underlined text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_u ($args)
    {

        return '<u>' . $this->_parse ('[/u]') . '</u>';
    }


    /**
     * show striken text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_s ($args)
    {

        return '<s>' . $this->_parse ('[/s]') . '</s>';
    }


    /**
     * show subscript text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_sub ($args)
    {

        return '<sub>' . $this->_parse ('[/sub]') . '</sub>';
    }


    /**
     * show superscript text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_sup ($args)
    {

        return '<sup>' . $this->_parse ('[/sup]') . '</sup>';
    }


    /**
     * show colored text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_color ($args)
    {

        // parse the text
        $text = $this->_parse ('[/color]');

        // check the color
        $color = (isset ($args['color'])) ? $args['color'] : false;
        // match it to a simple regex
        $color = (preg_match ('/^(?:#(?:[a-f0-9]{3}){1,2}|[a-z]{3,})$/i', $color))
            ?
$color
            : false;
        // return a span with the correct style if the color was correct
        return ($color !== false) ? '<span style="color: ' . $color . ';">' .
            $text . '</span>' : $text;
    }


    /**
     * show text with other size
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_size ($args)
    {

        // parse the text
        $text = $this->_parse ('[/size]');
        // get the size from the argument
        $size = (isset ($args['size'])) ? $size : '';

        // look if the size is correct
        switch ( $size )
        {

            // xsmall
            case 'xsmall':
                $size = '7px';
            break;
            // small
            case 'small':
                $size = '9px';
            break;
            // medium
            case 'medium':
                $size = '12px';
            break;
            // large
            case 'large':
                $size = '18px';
            break;
            // xlarge
            case 'xlarge':
                $size = '22px';
            break;
            default:

                return $text;
        }

        // return the span-ed text
        return '<span style="size: ' . $size . ';">' . $text . '</span>';
    }


    /**
     * show lists
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_list ($args)
    {

        // add an entry to our array
        $this->_in_tag['list']++;
        // parse 'till /list
        $text = $this->_parse ('[/list]', array ('li', 'li_short'));
        // remove this entry from the array
        $this->_in_tag['list']--;
        // check if we can find a type, either from the argument type, or list='type'
        $type = (isset ($args['list'])) ? $args['list'] : '';
        // if there was no correct type
        if (empty ($type) || $type == 'ul')
        {

            // we just return it unordered
            return '<ul>' . $text . '</ul>';
        }

        // otherwise, we return ordered
        return '<ol type="' . $type . '">' . $text . '</ol>';
    }


    /**
     * show a list item ([*])
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_li_short ($args)
    {

        // parse untill a linebreak
        $text = $this->_parse ("[linebreak\0]");
        // check if we're inside a list
        return ($this->_in_tag['list']) ? '<li>' . $text . '</li>' : $text;
    }


    /**
     * show a normal list item
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_li ($args)
    {

        // thesame as the previous tag, but now 'till the normal ender
        $text = $this->_parse ('[/li]');
        return ($this->_in_tag['list']) ? '<li>' . $text . '</li>' : $text;
    }


    /**
     * show a table
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_table ($args)
    {

        // cellpadding
        $padding = (isset ($args['padding']) && is_numeric ($args['padding']))
            ?
$args['padding']
            :
1;
        // cellspacing
        $spacing = (isset ($args['spacing']) && is_numeric ($args['spacing']))
            ?
$args['spacing']
            :
1;
        // border
        $border = (isset ($args['border']) && is_numeric ($args['border']))
            ?
$args['border']
            :
1;

        // add an entry to our array
        $this->_in_tag['table']++;
        // parse 'till /list
        $text = $this->_parse ('[/table]', array ('tr'));
        // remove this entry from the array
        $this->_in_tag['table']--;
        // return a correct piece
        return sprintf ('<table cellpadding="%s" cellspacing="%s" border="%s">%s</table>',
            $padding, $spacing, $border, $text);
    }


    /**
     * show a new table row
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_tr ($args)
    {

        $this->_in_tag['tr']++;
        // parse untill a linebreak
        $text = $this->_parse ('[/tr]', array ('td'));
        $this->_in_tag['tr']--;
        // check if we're inside a list
        return ($this->_in_tag['table']) ? '<tr>' . $text . '</tr>' : $text;
    }


    /**
     * show a td
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_td ($args)
    {

        // parse untill a linebreak
        $text = $this->_parse ('[/td]');
        // check if we're inside a list
        return ($this->_in_tag['tr']) ? '<td>' . $text . '</td>' : $text;
    }


    /**
     * show a line
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_line ($args)
    {

        // a normal tag, simple line
        return '<hr />';
    }


    /**
     * show a url
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_url ($args)
    {

        // 2 regexes to validate
        $regex = array (
             // links with: ftp http or https
            '~^(?:https?|ftp|irc)://[-a-z0-9+&@#/%?=\~_|!:,.;]*[-a-z0-9+&@#/%=\~_|]$~i',
            // url's that begin with www. or something like that
            '~^[-a-z0-9+&@#/%?=\~_|!:,.;]+[-a-z0-9+&@#/%=\~_|]$~i'
        );

        // check if it was set there
        if (!isset ($args['url']))
        {

            // if so, disable ubb_mode
            $this->_bb_mode = false;
        }

        // parse until /url
        $text = $this->_parse ('[/url]');
        // activate bb_mode no matter what
        $this->_bb_mode = true;

        // check the url with the argument and the given text
        $url = (isset ($args['url']))
            ?
$args['url']
            : (
                (!
empty ($text))
                ?
$text
                : false
            );

        // if no input was given
        if ($url === false)
        {

            // return '' (text is also empty;))
            return '';
        }


        // check the url with 2 regex, first with www, second without
        $url = (preg_match ($regex[0], $url))
            ?
$url
            : (
                (
preg_match ($regex[1], $url))
                ?
'http://' . $url
                : false
            );
        $text = (empty ($text)) ? $url : $text;

        return ($url !== false)
            ?
sprintf ('<a href="%s">%s</a>', $url, $text)
            :
$text;
    }


    /**
     * show bold text
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_email ($args)
    {

        $regex = '/^(?:[-a-z_][-a-z0-9._]*@[-a-z0-9_]+(?:\.[-a-z0-9_]+)+)$/si';

        // check if it was set there
        if (!isset ($args['email']))
        {

            // if so, disable ubb_mode
            $this->_bb_mode = false;
        }

        // parse until /url
        $text = $this->_parse ('[/email]');
        // activate bb_mode no matter what
        $this->_bb_mode = true;

        // check the url with the argument and the given text
        $email = (isset ($args['email']))
            ?
$args['email']
            : (
                (!
empty ($text))
                    ?
$text
                    : false
            );

        // if no input was given
        if ($email === false)
        {

            // return '' (text is also empty;))
            return '';
        }


        // check the email with the regex
        $email = (preg_match ($regex, $email)) ? $email : false;
        $text = (empty ($text)) ? $email : $text;

        return ($email !== false)
            ?
sprintf ('<a href="mailto:%s">%s</a>', $email, $text)
            :
$text;
    }


    /**
     * show an image
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_img ($args)
    {

        // drop out of bb_mode
        $this->_bb_mode = false;
        // get the url
        $img            = (isset ($args['img']))
            ?
$args['img']
            :
$this->_parse ('[/img]');

        $known_img_ext = array(    'jpg',
                                'gif',
                                'jpeg',
                                'png'
                            );
        
        // we only want img with ext. wich are in the $known_img_ext array so we get the ext. and check if the ext. is allowed
        $ext = substr (strrchr ($img, "."), 1);

        // go back into bb_mode
        $this->_bb_mode = true;
        
        if( in_array ($ext, $known_img_ext) AND !ereg('\?', $img) AND !ereg('\&', $img) ) { // if ext. is allowed
            
            // get some basic arguments

            $width          = (isset ($args['width'])) ? $args['width'] : 0;
            $height         = (isset ($args['height'])) ? $args['height'] : 0;
            $alt            = (isset ($args['alt'])) ? $args['alt'] : '';

            // create the return statement
            $return  = '<img src="' . $img . '"';
            $return .= ($width) ? ' width="' . $width . '"' : '';
            $return .= ($height) ? ' height="' . $height . '"' : '';
            $return .= ($alt) ? ' alt="' . $alt . '"' : '';
            $return .= ' />';
        }

        else {
            $return = "<div style='border: 1px solid red; background-color: #D3D3D3;'><div style='border: 1px solid red; border-bottom: 2px solid red; background-color: #FF8040; padding-left: 5px; padding-right: 5px; text-color: red; font-weight: bold;'>IMG ERROR:</div><div style='padding: 5px;'>";
            if( ereg('\&', $img) )
                $return .= "Sorry, er mag geen & teken in de bestandsnaam voorkomen!<br />";
            if( ereg('\?', $img) )
                $return .= "Sorry, er mag geen ? teken in de bestandsnaam voorkomen!<br />";
            if( !in_array($ext, $known_img_ext) )
                $return .= "Sorry, deze extentie (".$ext.") is niet toegestaan!<br />";
            $return .= "</div></div>";
        }

        // and return
        return $return;
    }


    /**
     * show a quote
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_quote ($args)
    {

        // set up arguments
        $args = array (
            'QUOTE_BY' => (isset ($args['quote']) && !empty ($args['quote']))
                ?
$args['quote']
                :
'Quote',
            'QUOTE_TEXT' => trim (preg_replace (
                '/(^\[linebreak\0]|\[linebreak\0]$)/',
                '',
                $this->_parse ('[/quote]')
            ),
"\r\n")
        );

        // return
        return $this->parse_bb_tpl ('quote', $args);
    }


    /**
     * show a code block
      * code may be highlighted with languages like
      * PHP, JAVA(script), CSS etc.
     *
     * @param    array    args
     * @return   string
     * @see      highlighter
    **/

    function _parse_bb_code ($args)
    {

        // drop out of bb_mode
        $this->_bb_mode = false;
        // this will parse from till the closer
        $code = $this->_parse ('');
        // go back in bb_mode
        $this->_bb_mode = true;

        // take further action to have correct code
        $code = trim (str_replace ("[linebreak\0]", "\n", $code), "\r\n");
        // check for a starting position
        $start = (isset ($args['s']) && $args['s'] > 0) ? $args['s'] : 1;
        // count the newlines
        $size = substr_count ($code, "\n");
        // update the size
        $size += $start;

        // should we highlight?
        if (!(isset ($args['highlight']) && $args['highlight'] == 'no'))
        {

            // default language is php, but can be different
            $language = (isset ($args['lang'])) ? $args['lang'] : 'php';

            // decode html entities
            $code = html_entity_decode ($code);
            // start the highlight object.. this does all the work
            $h = &new highlighter ($language, $code);
            // get the highlighted code
            $code = $h->get_code ();
        }

        // if we should't highlight
        else
        {
            $language = 'Geen highlighting';
            // do some basic stuff
            $code = str_replace ("\t", '    ', $code);
            $code = str_replace (' ', '&nbsp;', $code);
            $code = nl2br ($code);
        }


        // create lines
        $lines = '';
        // loop
        for ($i = $start; $i <= $size; $i++)
        {

            $lines .= $i . '<br />';
        }

        // take away last <br />
        $lines = substr ($lines, 0, -6);

        // argument assignment
        $args = array (
            'CODE_NAME' => (isset ($args['file']))
                ?
' (<i>' . $args['file'] . '</i>)'
                : '',
            'CODE_LANGUAGE' => $language,
            'CODE_ID' => 'field_' . $this->_curr_id++,
            'CODE_LEFT_WIDTH' => 14 + ((strlen ($size) - 1) * 8),
            'CODE_LINES' => $lines,
            'CODE_CONTENT' => $code,
        );


        // return parsed text
        return $this->parse_bb_tpl ('code', $args);
    }


    /**
     * show a block without parsing
     *
     * @param    array   $args
     * @return   string
    **/

    function _parse_bb_ignore ($args)
    {

        // drop out of bb_mode
        $this->_bb_mode = false;
        // parse until /ignore
        $text = $this->_parse ('[/ignore]');
        // go back into bb_mode
        $this->_bb_mode = true;
        // and simply return
        return $text;
    }


    /**#@-*/
}


/**
 * Highlighting class, supporting multiple
 * languages in the form of language files,
 * using regexes to match keywords etc.
 *
 * @author    JeXuS
 * @package   TP
**/

class highlighter
{
    /**#@+
     * @access   private
    **/

    /**
     * holds the language data
     *
     * @var      array     _data
    **/

    var $_data = array ();
    /**
     * holds the highlighted text
     *
     * @var      string    _highlighted
    **/

    var $_highlighted = '';
    /**
     * holds the inserted code
     *
     * @var      string    _code
    **/

    var $_code = '';
    /**
     * holds the style used for highlighting
     *
     * @var      string    _span
    **/

    var $_span = '<span style="%s">%s</span>';

    /**#@-*/

    /**#@+
     * @access   public
    **/

    /**
     * The constructor, this makes sure the language
     * file is included, and then begins the highlighting
     * process.
     *
     * @param    string   $language
     * @param    string   $code
     * @return   boolean
    **/

    function highlighter ($language, $code)
    {

        // the current directory
        $this_dir = str_replace ('\\', '/', dirname (__FILE__));

        // we prefer unix newlines
        $code = str_replace (array ("\r\n", "\r"), "\n", $code);
        // erase beginning and ending newlines
        $code = trim ($code, "\n");

        // check if the given language is an existing
        // language file

        if (!is_file ($language))
        {

            // if not, remove all non-alpanumeric character
            $language = preg_replace ('~[^A-Za-z0-9]+~', '', $language);
            // and convert it to lowercase
            $language = strtolower ($language);

            // take the directory we're in from the __FILE__ constant, and
            // append the filename we want

            $filename = "{$this_dir}/languages/{$language}.lang.php";

            // if the file doesn't exist...
            if (!is_file ($filename))
            {

                $this->_highlighted = nl2br (htmlspecialchars ($code));
                return true;
            }

            // if the file does exist
            else
            {
                // include it
                include $filename;
            }
        }

        // if the language is an existing file
        else
        {
            // include it
            include $language;
        }


        // if the language data isn't set
        if (!isset ($language_data))
        {

            $this->_highlighted = nl2br (htmlspecialchars ($code));
            return true;
        }


        // set the language data to our member
        $this->_data = $language_data;
        // prepare all language regexes
        $this->_prepare_language ();
        // put the code in our member
        $this->_code = $code;
        // memory saving
        $code = '';
        // walk through the code
        $this->_walk_through ();
        // cleanup and finish the code
        $this->_finish_code ();

        // and return true
        return true;
    }


    /**
     * return parsed code
     *
     * @return   string
    **/

    function get_code ()
    {

        return $this->_highlighted;
    }


    /**#@-*/

    /**#@+
     * @access   private
    **/

    /**
     * prepare language regexes
     *
     * @return   boolean
    **/

    function _prepare_language ()
    {

        // the things we need to go through
        $correct = array (
            'script_delim', 'comments', 'strings',
            'regexes', 'symbols', 'keywords'
        );

        // check if oo_splitters should be done
        if (isset ($this->_data['oo_splitters']) && count ($this->_data['oo_splitters']) > 0)
        {

            $this->_data['is_oo_lang'] = true;
            $correct[] = 'oo_splitters';
        }


        // loop through the parts
        foreach ($correct as $part)
        {

            // check if we've an array to loop, or just one thing
            if (isset ($this->_data[$part][0]) && !is_array ($this->_data[$part][0]))
            {

                // make it a regular regex, always starting at the beginning
                $this->_data[$part][0]  = '~^' . str_replace ('~', '\~', $this->_data[$part][0]) . '~';
                // try the dotall bit
                $this->_data[$part][0] .= ($this->_data[$part][1] & QBB_DOTALL) ? 's' : '';
                // and the caseless bit
                $this->_data[$part][0] .= ($this->_data[$part][1] & QBB_CASELESS) ? 'i' : '';
                // still make it an array
                $this->_data[$part] = array ($this->_data[$part][0]);
            }

            // if it's an array
            else
            {
                // loop through
                foreach ($this->_data[$part] as $i => $piece)
                {

                    // make it a regular regex, always starting at the beginning
                    $this->_data[$part][$i][0]  = '~^' . str_replace ('~', '\~', $this->_data[$part][$i][0]) . '~';
                    // try the dotall bit
                    $this->_data[$part][$i][0] .= ($this->_data[$part][$i][1] & QBB_DOTALL) ? 's' : '';
                    // and the caseless bit
                    $this->_data[$part][$i][0] .= ($this->_data[$part][$i][1] & QBB_CASELESS) ? 'i' : '';
                    // change it
                    $this->_data[$part][$i] = $this->_data[$part][$i][0];
                }
            }
        }

        return true;
    }


    /**
     * cleanup and finish code
     *
     * @return boolean
    **/

    function _finish_code ()
    {

        // if it's empty
        if (empty ($this->_highlighted))
        {

            // return false
            return false;
        }

        // loop as long as the regex is valid
        while (preg_match ('~(<span[^>]+>)([^<]+)</span>(\s*)\1~', $this->_highlighted, $match))
        {

            // concat all span's with thesame color next to it
            $this->_highlighted = str_replace ($match[0], $match[1] . $match[2] . $match[3],
                $this->_highlighted
            );
        }

        // replace tabs with four &nbsp;'s, and double spaces with 2 &nbsp;'s
        $this->_highlighted = str_replace (array ("\t", '  '), array ('&nbsp;&nbsp;&nbsp;&nbsp;', '&nbsp;&nbsp;'), $this->_highlighted);
        // graphical fix
        $this->_highlighted = str_replace ("\n ", "\n&nbsp;", $this->_highlighted);
        // nl2br, losing the \n
        $this->_highlighted = str_replace ("\n", '<br />', $this->_highlighted);
        // and return
        return true;
    }


    /**
     * checking if there's a valid match
     *
     * @param    integer   &$i
     * @param    array     $parts
     * @return   boolean
    **/

    function _check_for_match (&$i, $parts)
    {

        // the text to check
        $check_text = substr ($this->_code, $i);

        // loop through the parts given
        foreach ($parts as $part)
        {

            // go through the regexes
            foreach ($this->_data[$part] as $j => $regex)
            {

                // try to match
                if (preg_match ($regex, $check_text, $match))
                {

                    // if it's a match with a keyword, and there's a links availabe...
                    if ($part == 'keywords' && !empty ($this->_data['links'][$j]))
                    {

                        // create a valid link
                        $link = sprintf ($this->_data['links'][$j], urlencode ($match[0]));
                        // attach an underline style
                        $style = $this->_data['styles'][$part][$j] . ' text-decoration: underline;';
                        // the piece will be only a link, no span
                        $piece = '<a href="' . $link . '" style="' . $style . '" target="blank">' . htmlspecialchars ($match[0]) . '</a>';
                    }

                    // if it's a regular piece
                    else
                    {
                        // just a normal sprintf
                        $piece = sprintf (
                            $this->_span,
                            $this->_data['styles'][$part][$j],
                            htmlspecialchars ($match[0])
                        );
                    }


                    // append the piece
                    $this->_highlighted .= $piece;
                    // update &$i
                    $i += strlen ($match[0]) - 1;
                    // return true
                    return true;
                }
            }
        }


        // return false
        return false;
    }


    /**
     * walk through the code, searching
     * for all kinds of things, comments,
     * strings, keywords etc.
     *
     * @return   boolean
    **/

    function _walk_through ()
    {

        // fixed length
        $length = strlen ($this->_code);

        // we're not in highlighting
        $in_highlighting = false;
        // should we check for delimiters
        $check_delim = true;
        // if the delimiters array is empty
        if (count ($this->_data['script_delim']) == 0)
        {

            // we always highlight
            $in_highlighting = true;
            // we don't check on delimiters
            $check_delim = false;
            // prepend the default color now
            $this->_highlighted .= '<span style="' . $this->_data['styles']['overall'] . '">';
        }


        // loop through
        for ($i = 0; $i < $length; $i++)
        {

            // take a big chunk of remaining code
            $text = substr ($this->_code, $i);
            // take the first character
            $first = substr ($text, 0, 1);
            // previous character
            $prev = substr ($this->_code, $i - 1, 1);

            // check if the first character is a space
            if (ctype_space ($first))
            {

                // if so, append it
                $this->_highlighted .= $first;
                // and continue
                continue;
            }

            /** note: the above increases speed a LOT **/

            // should we check for delimiters...

            if ($check_delim === true && $in_highlighting === false)
            {

                // if we match a delimiter
                if (preg_match ($this->_data['script_delim']['start'], $text, $match))
                {

                    // append it to the source
                    $this->_highlighted .= '<span style="' . $this->_data['styles']['overall'] . '">';
                    // we're in highlighting
                    $in_highlighting = true;
                    // we need to start here again with highlighting
                    $i--;
                    // free ourselves from the loop
                    continue;
                }

                // append the first character
                $this->_highlighted .= htmlspecialchars ($first);
                // and continue
                continue;
            }


            // check if in highlighting
            if ($in_highlighting === true)
            {

                // check this last
                if ($check_delim === true)
                {

                    // try to match an ending delimiter
                    if (preg_match ($this->_data['script_delim']['end'], $text, $match))
                    {

                        // if matched, append it to the current code
                        $this->_highlighted .= htmlspecialchars ($match[0]) . '</span>';
                        // we've skipped out of highlighting
                        $in_highlighting = false;
                        // update counter
                        $i += strlen ($match[0]) - 1;
                        // go to the beginning of the loop
                        continue;
                    }
                }


                // in which parts should we look?
                $find = array ('comments', 'strings', 'regexes');
                // simple check if we MAY match keywords
                if (!ctype_alpha ($prev) && $prev != '_')
                {

                    // if correct, add it
                    $find[] = 'keywords';
                }


                // check for a match, give $i by reference
                if ($this->_check_for_match ($i, $find))
                {

                    // if matched, continue
                    continue;
                }


                // if we've got a `punct` character
                if (ctype_punct ($first))
                {

                    // check if this is an OO lang
                    if (isset ($this->_data['is_oo_lang']))
                    {

                        // if so, try to match a object splitter
                        if (preg_match ($this->_data['oo_splitters'][0], $text, $match))
                        {

                            // if matched, append this piece
                            $this->_highlighted .= sprintf (
                                $this->_span,
                                $this->_data['styles']['oo_splitters'][0],
                                htmlspecialchars ($match[0])
                            );

                            // update $i
                            $i += strlen ($match[0]) - 1;

                            // new piece, not very long
                            $text = substr ($this->_code, $i, 100);
                            // try to match a method/child
                            if (preg_match ('~^[a-z*(_][a-z0-9_*]*~i', $text, $match))
                            {

                                // if matched, append it
                                $this->_highlighted .= sprintf (
                                    $this->_span,
                                    $this->_data['styles']['oo_methods'][0],
                                    htmlspecialchars ($match[0])
                                );

                                // update $i
                                $i += strlen ($match[0]) - 1;
                            }

                            // continue in both cases
                            continue;
                        }
                    }


                    // loop through all symbols
                    foreach ($this->_data['symbols'] as $j => $regex)
                    {

                        // if we find a valid match
                        if (preg_match ($regex, $text, $match))
                        {

                            // if match, append |* starts to get boring
                            $this->_highlighted .= sprintf (
                                $this->_span,
                                $this->_data['styles']['symbols'][$j],
                                htmlspecialchars ($match[0])
                            );

                            // update $i
                            $i += strlen ($match[0]) - 1;
                            // jump out of this loop, and continue the outer
                            continue 2;
                        }
                    }
                }


                // simple check
                if (!ctype_alnum ($prev))
                {

                    // try to match an integer/float
                    if (preg_match ('~^(?:0x[0-9A-Fa-f]+|[0-9]+(?:\.[0-9]+)?)~', $text, $match))
                    {

                        // if matched, append
                        $this->_highlighted .= sprintf (
                            $this->_span,
                            $this->_data['styles']['numbers'],
                            htmlspecialchars ($match[0])
                        );

                        // update $i
                        $i += strlen ($match[0]) - 1;
                        // continue
                        continue;
                    }
                }
            }

            // append this character
            $this->_highlighted .= htmlspecialchars (substr ($this->_code, $i, 1));
        }

        // if we're still in highlighting
        if ($in_highlighting === true)
        {

            // append a closing span
            $this->_highlighted .= '</span>';
        }


        // return
        return true;
    }


    /**#@-*/
}
// ** EOF **
?>
Pascal
Pascal
20 jaar geleden
 
0 +1 -0 -1
Mooie script alleen bij mij gaat die foutmelding geven in : text_parser.class.php

als ik dit gebruik om te testen :

Code (php)
PHP script in nieuw venster Selecteer het PHP script
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
<?php
require_once 'text_parser.class.php'; // includen
$bb = &new bbcode; // bbcode_tpl.htm is de standaard
$text = <<<EOT
[code lang='php']
<?php
echo 'test';
?>
[/ code]
EOT
;

echo $bb->parse ($text);
?>


edit : heb het gemaakt :) !
Alexander
Alexander
19 jaar geleden
 
0 +1 -0 -1
ik heb een probeel met dit script,
als ik php code ermee parse dan vertaalt php de variablen alsnog,
hierdoor wordt mijn code niet goed weer gegeven,
ik heb niks what so ever aangepast aan het bestand:
$var is dus een variable, die dus geparsed word en undefined errors eruit gooien..
Afbeelding

ik hoop dat de foto het duidelijk maakt,
dit is de code die ik gebruik, ik heb verschillende opzetten geprobeerd:
Code (php)
PHP script in nieuw venster Selecteer het PHP script
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
<?php

$text
= <<<EOT

[b]Deze text is bold[/b].

[url='http://www.jexus.net']JeXuS[/url]

[quote='JeXuS']

Dit werd door JeXuS geschreven:

[quote=n00b]

En dit door een n00b

[/quote]

[/quote]





<?php
echo 'dit is een test';

$var = 'my var';

while($var != 'myvar') {

    echo 'my var is not my var!';

}
?>



EOT
;



echo $bb->parse($text);

?>

de code tags staan om de php tags alleen die worden door de script op deze site eruit gefilterd...
ik dacht, laat ik even vragen voordat ik door 1500 regels code ga ploeteren!
Simon
Simon
19 jaar geleden
 
0 +1 -0 -1
Er zit een klein probleempje in, als een quote= argument een spatie bevat, word alleen het eerste woord weergegeven, de rest word domweg uit de tekst weggelaten.

Ik ben er nog niet helemaal uit hoe dit op te lossen, aangezien ik de code nog niet helemaal goed heb nagelopen.
Richard van Velzen
Richard van Velzen
19 jaar geleden
 
0 +1 -0 -1
Ondanks het feit dat ik dit hier bijna 2 jaar geleden heb neergezet, daar nog even een reactie op. :-)

Als je een parameter aan een tag wil meegeven waar spaties in voorkomen, ben je genoodzaakt om quotes er omheen te zetten. Het is wel te veranderen, maar ik onderhoud dit script niet meer, dus ik ga het zelf niet doen. Alles wat je moet doen bevindt zich in de _parse_bb_arguments methode.

Op http://www.liefcoden.nl/ubb/ kun je de voortgang van m'n laatste parser volgen. ;)
Simon
Simon
19 jaar geleden
 
0 +1 -0 -1
Tja, sorry dat't zo lang heeft geduurd ;)
Ik heb nou eenmaal nu pas echt nut voor je script, ik heb jaren gewerkt met m'n eigen code, maar deze begon zoveel tekortkomingen te vertonen, dat ik maar ben begonnen met overschakelen naar jou script.

De quotes er omheen werken dus niet ;) anders had ik het wel voor elkaar gekregen, maar dat gaat blijkbaar ergens mis.

Nou ja, ik werk er wel aan, heb toch nog zat te doen, aangezien jou code ook nog eens een globalizing vereist (waarom eigenlijk?)
PHP hulp
PHP hulp
0 seconden vanaf nu
 

Gesponsorde koppelingen
Richard van Velzen
Richard van Velzen
19 jaar geleden
 
0 +1 -0 -1
Don't ask, het is niet voor niets zo oud. ;)

Om te reageren heb je een account nodig en je moet ingelogd zijn.

Inhoudsopgave

  1. bbcode-parser-highlighter

Labels

  • Geen tags toegevoegd.

Navigatie

 
 

Om de gebruiksvriendelijkheid van onze website en diensten te optimaliseren maken wij gebruik van cookies. Deze cookies gebruiken wij voor functionaliteiten, analytische gegevens en marketing doeleinden. U vindt meer informatie in onze privacy statement.