Форум: Форум PHPФорум ApacheФорум Регулярные ВыраженияФорум MySQLHTML+CSS+JavaScriptФорум FlashРазное
Новые темы: 0000000
Объектно-ориентированное программирование на PHP. Авторы: Кузнецов М.В., Симдянов И.В. PHP Puzzles. Авторы: Кузнецов М.В., Симдянов И.В. PHP на примерах (2 издание). Авторы: Кузнецов М.В., Симдянов И.В. PHP 5. На примерах. Авторы: Кузнецов М.В., Симдянов И.В., Голышев С.В. Самоучитель MySQL 5. Авторы: Кузнецов М.В., Симдянов И.В.
ВСЕ НАШИ КНИГИ
Консультационный центр SoftTime

Разное

Выбрать другой форум

 

Здравствуйте, Посетитель!

вид форума:
Линейный форум Структурный форум

тема: Нумерация строк кода на форуме
 
 автор: sim5   (28.07.2009 в 04:08)   письмо автору
166.2 Кб
 
 

Ну в общем достало.... :)
Скачал LiteForum, и в основном все, что я хотел, я добавил. Пока не все окончательно доделано, а времени тоже нет, и может выставить готовое, чтобы подключились другие, кому надоело копировать из поста в пост куски кода? Ну если нет таковых, доделаю сам, и если Хеопс.... Впрочем о фараонах потом :)

И так, что сделано:
1. Добавлены теги S, U, SUP, SUB, PRE, ABBR, SAMP. Верхнее подчеркивание и вставка html-пердставления реализуются за счет элементов SPAN. Собственно все теги неимеющиеся в HTML реализуются за счет них, включая подсветку кода.
2. Вставка тегов осуществляется из меню, при чем стартовый номер строки кода, url ссылки, расшифровка аббревиатуры происходит из дополнительного запроса, в котором нужно ввести соответствующее значение. От стандартного PROMPT я отказался по той причине, что в него нельзя ввести много сопровождающего текста. Ну а как показало время, вновь приходящие на форум не всегда знают, что за ВВ-теги и для чего они служат. "Искусственный промт" позволяет вывести такую пояснительную информацию.
3. По умолчанию код начинается с нулевой строки, при этом пробелы предшествующие тегам CODE и после него обрезаются. Не думаю, что это недостаток, если будет выставляться код, например, с ошибкой связанной с передачей заголовка (пробел перед тегом), так как и при вводе реального номера для стартовой строки, или по умолчанию, будет видно несоответствие - смещение кода по отношению к строке с ошибкой. Да и не очень выглядит, как сейчас на форуме, пустота перед кодом.
4. На   заменяются только ведущие слева пробелы, остальные не учитываются. Я не знаю причины, по которой бы нужно было учитывать все пробелы в строке кода. Для вставки в сообщение просто форматированного текста добавлен ВВ-тег для PRE. При этом такой тег в теге CODE (при его наличии) вырезается. Хватит прокручивать портянки с кодом, а длинная строка кода в элементе LI будет автоматически перенесена, не нарушая при этом нумерации.
4. Цитирование автора - теперь это выделение необходимого в его сообщении и щелчек по ссылке "Цитировать", а не весь заготовленный на сервере текст. В браузерах FF, Opera и Safari выделеный текст отмечается краснным цветом (за счет селекторов CSS3). Правда в Safari (по крайней мере в последней) немного странно выглядит выбор элементов LI, в которые обрамлены строки кода, но сейчас нет необходимости цитировать код автора, достаточно указать номер/номера строк :) Цитируемый текст выделяется за счет стиля и обрамляется кавычками « ».
Наблюдал странность в IE8 - при копировании кода непосредственно из сообщения копируются и номера строк, а при копировании для цитирования нет. Правда, может это связано с работой какого либо плагина к нему, не разбирался.

В прикрепленном рисунке видно на примерах как сейчас все выглядит.

Собственно осталась подсветка. Я задействовал (так понимаю не до конца доработанную) функцию cpp_highlight(). На рисунке видно, что в комментарии во втором случае слово "массива" было определено как функция, во второй строке первого поста также в комментарии подсвечено array(), хотя в комментариях уже должен быть исключен поиск выражений, функций и т.п.. При чем это не связано с тем, что теперь код разбит на строки, то же самое происходило и до этого, при разборе кода неразбитого на отдельные строки. Вообще, на рисунке заметно, что ошибки всегда присутсвуют при разборе строк заключенных в кавычки.

За основу я взял стиль подсветки как в HomeSite - спокойный, не кричащий комментариями и строками, которые по сути второстепенные. Главный оличительный цвет, это РНР-теги, позволяющие хорошо обнаруживать вставку кода. Собственно, как я уже говорил, все стили можно поменять через CSS.

Вот подсветку и осталось сделать. Полностью рег. выражениями не получится, так как тот же комментарий или SQL запрос, может быть перенесен на несколько строк, а значит нужно обрабатывать все кусками, запоминать и передавать обработчику состояние незавершенной обработки строки, если она заканчивается в NN-строке (то же QSL запрос).

Я примерно набросал себе как это буду делать (включая подсветку и JS), но может у кого идеи будут, то хорошо, собственно с этой целю и написал сие. А то только одна борьба с непарными тегами Р в исходнике какой крови стоит, устал. :)

  Ответить  
 
 автор: Commander   (28.07.2009 в 09:46)   письмо автору
 
   для: sim5   (28.07.2009 в 04:08)
 

Sim5, вы молодец. Меня давно подмывало сделать что-то подобное, но времени (а может и желания, терпения, [руки не доходят] (нужное подчеркнуть :))) не хватает. Впрочем, у меня есть пара идей для своего форума, в этот движок, наверное тоже добавлю и отправлю cheops'у.

Короче, есть идея добавить поддержку тегов форматирования текста. Имеются в виду не bbCode, а теги HTML. Также можно было бы добавить тег цитаты. Знай я рег. выражения получше, добавил бы и подсветку HTML, CSS и JavaScript - кода.

P.S. Вам же не нравится нечисть колобОчная, а на скриншоте она есть.

  Ответить  
 
 автор: sim5   (28.07.2009 в 13:31)   письмо автору
 
   для: Commander   (28.07.2009 в 09:46)
 

Было бы конечно хорошо, чтобы и HTML элементы подсвечивались, и я бы сделал это так же (повторюсь) как в HomeSite. В нем из всех таких элементов выделяется форма, ее элементы.... Но это усложнит работу, а одному писать и проверять РНР и JS, бороться с сепаратизмом разных браузеров и т.п. трудно, так что моя задача - подсветка РНР и JS, остальное коллективная инициатива :)

Да, здесь на форуме они (колобки) лишние, но это не значит, что я ими не пользуюсь. Он в примере для примера, как и остальные html-представления.
Действительно, бывает крайняя необходимость написать матиматическое или логическое выражение, и без html-представлений на данном форуме не обойтись. Нет нужды описывать как было составлено выражение квадратного корня в примере, все просто. Вопрос только в самом механизме вставки.... А ведь это сделать можно с помощью JS, типа так как в Ворде и прочих редакторах - "вставить символ", я это могу добавить, но.... Вот получите все html-представления:

<?
$f 
fopen("html_ent.html""w");
$s "<html><body><table border=0 cellpadding=4 cellspacing=1 bgcolor=#000000>";
$e "&amp;#";
for (
$i=0$i<10000$i++) {
  if(!(
$i 12)) $s .= "<tr bgcolor=#ffffff>";
  
$s .= "<td bgcolor=#E2E2E2 style=\"color: #800000;\">"str_replace("&amp;#""&#"$e).$i ";</td><td>"$e.$i ";</td>";
  if(!((
$i+1) % 12)) $s .= "</tr>";
}
$s .= "</table></body></html>";
fputs($f$s);
fclose($f);

Из полученной таблицы руками удалите строки с "квадратиками", затем нужно будет из всех символов полученных отобрать только те, которые действительно будут полезны на форуме, в его контексте. А уже список отобранных и сгруппированных символов (математические, графические, прочие....) прикрепите здесь, а я сделаю вставку символов. Заниматься всем одному сложно, сами понимаете.

  Ответить  
 
 автор: Вот случайно зашел   (26.08.2009 в 11:02)   письмо автору
 
   для: Commander   (28.07.2009 в 09:46)
 

А зачем нужна функция highlight_string()?

highlight_string

(PHP 4, PHP 5)

highlight_string — Syntax highlighting of a string
Description
mixed highlight_string ( string $str [, bool $return= false ] )

Outputs or returns a syntax highlighted version of the given PHP code using the colors defined in the built-in syntax highlighter for PHP.
Parameters

str

The PHP code to be highlighted. This should include the opening tag.
return

Set this parameter to TRUE to make this function return the highlighted code.

Return Values

If return is set to TRUE, returns the highlighted code as a string instead of printing it out. Otherwise, it will return TRUE on success, FALSE on failure.
Changelog
Version Description
4.2.0 The return parameter was added.


Examples


Example #1 highlight_string() example
<?php
highlight_string('<?php phpinfo(); ?>');
?>

The above example will output (in PHP 4):
<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">(); </font><font color="#0000BB">?&gt;</font>
</font>
</code>

The above example will output (in PHP 5):
<code><span style="color: #000000">
<span style="color: #0000BB">&lt;?php phpinfo</span><span style="color: #007700">(); </span><span style="color: #0000BB">?&gt;</span>
</span>
</code>

Notes

Note: This function uses internal output buffering with this parameter so it can not be used inside an ob_start() callback function.
See Also

highlight_file() - Syntax highlighting of a file



ignore_user_abort
highlight_file
Last updated: Fri, 14 Aug 2009

add a note
User Contributed Notes
highlight_string
Mean^_^
19-Apr-2009 04:45
[EDIT BY danbrown AT php DOT net: The following note contains a user-supplied version of a syntax highlighter.]

<style type="text/css">
.linenum{
text-align:right;
background:#FDECE1;
border:1px solid #cc6666;
padding:0px 1px 0px 1px;
font-family:Courier New, Courier;
float:left;
width:17px;
margin:3px 0px 30px 0px;
}

code {/* safari/konq hack */
font-family:Courier New, Courier;
}

.linetext{
width:700px;
text-align:left;
background:white;
border:1px solid #cc6666;
border-left:0px;
padding:0px 1px 0px 8px;
font-family:Courier New, Courier;
float:left;
margin:3px 0px 30px 0px;
}

br.clear {
clear:both;
}

</style>
<?php

function printCode($code, $lines_number = 0) {

if (!is_array($code)) $codeE = explode("\n", $code);
$count_lines = count($codeE);

$r1 = "Code:<br />";

if ($lines_number){
$r1 .= "<div class=\"linenum\">";
foreach($codeE as $line =>$c) {
if($count_lines=='1')
$r1 .= "1<br>";
else
$r1 .= ($line == ($count_lines - 1)) ? "" : ($line+1)."<br />";
}
$r1 .= "</div>";
}

$r2 = "<div class=\"linetext\">";
$r2 .= highlight_string($code,1);
$r2 .= "</div>";

$r .= $r1.$r2;

echo "<div class=\"code\">".$r."</div>\n";
}

printCode('<?php echo "PHP Code" ?> ',1);
?>

by mean
Share idea.
good luck ^_^
Dmitry S
24-Jul-2008 08:38
Alternative XML syntax highlighting.

<?php
function xml_highlight($s)
{
$s = htmlspecialchars($s);
$s = preg_replace("#&lt;([/]*?)(.*)([\s]*?)&gt;#sU",
"<font color=\"#0000FF\">&lt;\\1\\2\\3&gt;</font>",$s);
$s = preg_replace("#&lt;([\?])(.*)([\?])&gt;#sU",
"<font color=\"#800000\">&lt;\\1\\2\\3&gt;</font>",$s);
$s = preg_replace("#&lt;([^\s\?/=])(.*)([\[\s/]|&gt;)#iU",
"&lt;<font color=\"#808000\">\\1\\2</font>\\3",$s);
$s = preg_replace("#&lt;([/])([^\s]*?)([\s\]]*?)&gt;#iU",
"&lt;\\1<font color=\"#808000\">\\2</font>\\3&gt;",$s);
$s = preg_replace("#([^\s]*?)\=(&quot;|')(.*)(&quot;|')#isU",
"<font color=\"#800080\">\\1</font>=<font color=\"#FF00FF\">\\2\\3\\4</font>",$s);
$s = preg_replace("#&lt;(.*)(\[)(.*)(\])&gt;#isU",
"&lt;\\1<font color=\"#800080\">\\2\\3\\4</font>&gt;",$s);
return nl2br($s);
}
?>
fsx dot nr01 at gmail dot com
13-Jun-2008 04:22
Here is an improved version of the code highlighter w/ linenumbers from 'vanessaschissato at gmail dot com' - http://nl.php.net/manual/en/function.highlight-string.php#70456

<?php

function printCode($source_code)
{

if (is_array($source_code))
return false;

$source_code = explode("\n", str_replace(array("\r\n", "\r"), "\n", $source_code));
$line_count = 1;

foreach ($source_code as $code_line)
{
$formatted_code .= '<tr><td>'.$line_count.'</td>';
$line_count++;

if (ereg('<\?(php)?[^[:graph:]]', $code_line))
$formatted_code .= '<td>'. str_replace(array('<code>', '</code>'), '', highlight_string($code_line, true)).'</td></tr>';
else
$formatted_code .= '<td>'.ereg_replace('(&lt;\?php&nbsp;)+', '', str_replace(array('<code>', '</code>'), '', highlight_string('<?php '.$code_line, true))).'</td></tr>';
}

return '<table style="font: 1em Consolas, \'andale mono\', \'monotype.com\', \'lucida console\', monospace;">'.$formatted_code.'</table>';
}

?>
Dobromir Velev
27-May-2008 11:04
Here is an improved version of Dimitry's xml_highlight function.
I fixed a bug which replaced the first character of the tags name,
and added a line to replace the tabs and spaces with
non-breaking space symbols to keep the identation.

<?
function xml_highlight($s){
$s = preg_replace("|<([^/?])(.*)\s(.*)>|isU", "[1]<[2]\\1\\2[/2] [5]\\3[/5]>[/1]", $s);
$s = preg_replace("|</(.*)>|isU", "[1]</[2]\\1[/2]>[/1]", $s);
$s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]", $s);
$s = preg_replace("|\=\"(.*)\"|isU", "[6]=[/6][4]\"\\1\"[/4]",$s);
$s = htmlspecialchars($s);
$s = str_replace("\t","&nbsp;&nbsp;",$s);
$s = str_replace(" ","&nbsp;",$s);
$replace = array(1=>'0000FF', 2=>'0000FF', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
foreach($replace as $k=>$v) {
$s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU", "<font color=\"#".$v."\">\\1</font>", $s);
}

return nl2br($s);
}
?>
Dmitry S
12-May-2008 01:29
The simple XML syntax highlighting.

<?php
function xml_highlight($s)
{
$s = preg_replace("|<[^/?](.*)\s(.*)>|isU","[1]<[2]\\1[/2] [5]\\2[/5]>[/1]",$s);
$s = preg_replace("|</(.*)>|isU","[1]</[2]\\1[/2]>[/1]",$s);
$s = preg_replace("|<\?(.*)\?>|isU","[3]<?\\1?>[/3]",$s);
$s = preg_replace("|\=\"(.*)\"|isU","[6]=[/6][4]\"\\1\"[/4]",$s);
$s = htmlspecialchars($s);
$replace = array(1=>'0000FF', 2=>'808000', 3=>'800000', 4=>'FF00FF', 5=>'FF0000', 6=>'0000FF');
foreach($replace as $k=>$v)
{
$s = preg_replace("|\[".$k."\](.*)\[/".$k."\]|isU","<font color=\"".$v."\">\\1</font>",$s);
}
return nl2br($s);
}
?>
Daniel
20-Feb-2008 10:49
Well, Just a little something I wrote which highlights an HTML code...It'll be going through many changes in the next few days.... until then =) enjoy

<?php
/*************************************\
CODE PANE 1.0 - SILVERWINGS - D. Suissa
\*************************************/

class HTMLcolorizer{
private $pointer = 0; //Cursor position.
private $content = null; //content of document.
private $colorized = null;
function __construct($content){
$this->content = $content;
}
function colorComment($position){
$buffer = "&lt;<span class='HTMLComment'>";
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
$buffer.= $this->content[$position];
}
$buffer .= "</span>&gt;";
$this->colorized .= $buffer;
return $position;
}
function colorTag($position){
$buffer = "&lt;<span class='tagName'>";
$coloredTagName = false;
//As long as we're in the tag scope
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
if($this->content[$position] == " " && !$coloredTagName){
$coloredTagName = true;
$buffer.="</span>";
}else if($this->content[$position] != " " && $coloredTagName){
//Expect attribute
$attribute = "";
//While we're in the tag
for(;$position < strlen($this->content) && $this->content[$position] != ">" ;$position++){
if($this->content[$position] != "="){
$attribute .= $this->content[$position];
}else{
$value="";
$buffer .= "<span class='tagAttribute'>".$attribute."</span>=";
$attribute = ""; //initialize it
$inQuote = false;
$QuoteType = null;
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != " " ;$position++){
if($this->content[$position] == '"' || $this->content[$position] == "'"){
$inQuote = true;
$QuoteType = $this->content[$position];
$value.=$QuoteType;
//Read Until next quotation mark.
for($position+=1;$position < strlen($this->content) && $this->content[$position] != ">" && $this->content[$position] != $QuoteType ;$position++){
$value .= $this->content[$position];
}
$value.=$QuoteType;
}else{//No Quotation marks.
$value .= $this->content[$position];
}
}
$buffer .= "<span class='tagValue'>".$value."</span>";
break;
}

}
if($attribute != ""){$buffer.="<span class='tagAttribute'>".$attribute."</span>";}
}
if($this->content[$position] == ">" ){break;}else{$buffer.= $this->content[$position];}

}
//In case there were no attributes.
if($this->content[$position] == ">" && !$coloredTagName){
$buffer.="</span>&gt;";
$position++;
}
$this->colorized .= $buffer;
return --$position;
}
function colorize(){
$this->colorized="";
$inTag = false;
for($pointer = 0;$pointer<strlen($this->content);$pointer++){
$thisChar = $this->content[$pointer];
$nextChar = $this->content[$pointer+1];
if($thisChar == "<"){
if($nextChar == "!"){
$pointer = $this->colorComment($pointer);
}else if($nextChar == "?"){
//colorPHP();
}else{
$pointer = $this->colorTag($pointer);
}
}else{
$this->colorized .= $this->content[$pointer];
}
}
return $this->colorized;
}
}
$curDocName = $_REQUEST['doc'];
$docHandle = fopen($curDocName,"r");
$docStrContent = fread($docHandle,filesize($curDocName));
fclose($docHandle);
$HTMLinspector = new HTMLcolorizer($docStrContent);
$document = $HTMLinspector->colorize();
?>

<html>
<head>
<style type="text/css">
/**********************\
* MOZILLA FIREFOX STYLE
\**********************/
/*pre{font-family:Tahoma;font-size:px;}*/
.tagName{color:purple;}
.tagAttribute{color:red;}
.tagValue{color:blue;}
.HTMLComment{font-style:italic;color:green;}
</style>
</head>
<body>
<?php
echo "<pre>".$document."</pre>";
?>
</body>
</html>
wm at tellinya dot com
17-Dec-2007 12:32
I wanted to build a better function and exclude operators {}=- from keywords span class. I also wanted to link functions used in my PHP code directly to the PHP site.
A lot more changes and tweaks have been made and the output is much better!

Find the function here :
http://www.tellinya.com/art2/262/highligh-php-syntax/
and ditch the old PHP one permanently.
Tested and built on PHP 5.2.0.

Looking forward to any input.
phpnotes dot 20 dot zsh at spamgourmet dot com
19-Sep-2007 03:05
peter at int8 dot com > "This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet."

It does also require enabled open/close tags. For example:

<?php
highlight_string('<? echo "Hello world!";?>');
?>

Won't work with short_open_tag = Off. Compare example 10.2 on:
Main mirror (http://www.php.net/manual/en/language.basic-syntax.php#id2530407)
US mirror (http://us.php.net/manual/en/language.basic-syntax.php#id2530407)
IN mirror (http://in.php.net/manual/en/language.basic-syntax.php#id2530407)
www.phella.net
06-Sep-2007 03:47
When you quote highlighted PHP code in your website you need to escape quotes. If you quote a lot it may be annoyning. Here is tiny snippet how to make quoting tidy and clean. Write your code like this:

<?code()?>
$string = 'Here I put my code';
<?code()?>

And somewhere else define the function:

<?
function code()
{
static $on=false;
if (!$on) ob_start();
else
{
$buffer= "<?\n".ob_get_contents()."?>";
ob_end_clean();
highlight_string($buffer);
}
$on=!$on;
}
?>
dark_messenger84 at yahoo dot co dot uk
02-Sep-2007 08:31
Here's an improved version of supremacy2k at gmail dot com's code. It's a small function that accepts either PHP syntax in plain text or from another script, and then parses it into an ordered list with syntax highlighting.

<?php
function print_php_code($str, $type) {
switch ($type) {
case "text":
$str = highlight_string($str, true);
break;
case "file":
$str = highlight_file($str, true);
break;
}
$str = explode("<br />", $str);
echo "<div>";
echo "<ol>\n";
foreach ($str as $line => $syntax) {
echo "<li><code>" . $syntax . "</code></li>";
}
echo "</ol>\n";
echo "</div>";
}
?>
supremacy2k at gmail dot com
01-Apr-2007 12:06
A simplification of functions vanessaschissato at gmail dot com at 17-Oct-2006 05:04.

Since it had trouble keeping the code intact. (It removed /* )

function showCode($code) {
$code = highlight_string($code, true);
$code = explode("<br />", $code);

$i = "1";
foreach ($code as $line => $syntax) {
echo "<font color='black'>".$i."</font> ".$syntax."<br>";
$i++;
}
}
Pyerre
04-Mar-2007 09:29
This fonction replaces every space with the html code &nbsp; (non-breaking space)
this is not very good because text will not go to the line and causes a big width
for example in a bordered div, text will go across the border

my solution :
echo str_replace("&nbsp;", " ",highlight_string("Arise, you children of the fatherland",true));
echo str_replace("&nbsp;", " ",highlight_file("test.php",true));
vanessaschissato at gmail dot com
17-Oct-2006 03:04
This class show a code formated.
Allow options for to format.
Options: highlight code and to show line number

<?php

class Code
{

function printCode($code, $high_light = 0, $lines_number = 0)
{
if (!is_array($code)) $code = explode("\n", $code);

$count_lines = count($code);

foreach ($code as $line => $code_line) {

if ($lines_number) $r1 = "<span class=\"lines_number\">".($line + 1)." </span>";

if ($high_light) {
if (ereg("<\?(php)?[^[:graph:]]", $code_line)) {
$r2 = highlight_string($code_line, 1)."<br />";
} else {

$r2 = ereg_replace("(&lt;\?php&nbsp;)+", "", highlight_string("<?php ".$code_line, 1))."<br />";

}
} else {
$r2 = (!$line) ? "<pre>" : "";
$r2 .= htmlentities($code_line);
$r2 .= ($line == ($count_lines - 1)) ? "<br /></pre>" : "";
}

$r .= $r1.$r2;

}

echo "<div class=\"code\">".$r."</div>";
}
}

?>
tyler dot reed at brokeguysinc dot com
02-Oct-2006 01:11
This is a little chunk of code that i use to show the source of a file, i took part of the idea from a example i found on another php function page.

This code takes a php file and highlights it and places a line number next to it. Great for on the fly debugging.

<?php
// Get a file into an array
$lines = file('index.php');

// Loop through our array, show HTML source as HTML source; and line numbers too.
echo('<table border=0 cellpadding=0 cellspacing=0>');
foreach ($lines as $line_num => $line) {
echo('<tr>');
echo('<td bgcolor = "#cccccc">');
echo('<code>' . ($line_num + 1) . '</code>');
echo('</td>');
echo('<td>');
highlight_string($line);
echo('</td>');
echo('</tr>');
}

?>
thomas et luegger _dot_ de
20-Jul-2006 12:20
Thanks to peter at int8 dot com, your comment saved quite some time.

In my case even short tags didn't work right (PHP 5.0.5).

The following function offers subversion independent highlighting for PHP5. If you want to display code snippets without tags or use css for code formating it might be a usefull starting point. It is intented for small code fragments only and does not handle sources with multiple php blocks correctly.

Beware, the <code> tag is stripped off.

<?php

/*

These classes are used for highlighting, happy css-ing:

.phpdefault { color:#0000BB; font-weight: bold;}
.phpkeyword { color:#007700; font-weight: bold;}
.phpstring { color:#DD0000; font-weight: normal;}
.phpcomment { color:#FF8000; font-weight: normal;}

*/

/**
* Highlights PHP-source snippets with and without php-tags, inserts class definitions on request
*
* Strips <code> and <span color:black>, removes empty spans
*
* @param string $source Source to highlight
* @param boolean $classes, true links source elements to classes
* @return string
*/
function php_highlight($source, $classes = false)
{
if (version_compare( phpversion(), "5.0.0", "<")) return "PHP 5 required";

$r1 = $r2 = '##';

// adds required PHP tags (at least with vers. 5.0.5 this is required)
if ( strpos($source,' ?>') === false ) // xml is not THAT important ;-)
{
$source = "<?php ".$source." ?>";
$r1 = '#&lt;\?.*?(php)?.*?&nbsp;#s';
$r2 = '#\?&gt;#s';
}
elseif (strpos($source,'<? ') !== false)
{
$r1 = '--';
$source = str_replace('<? ','<?php ',$source);
}

$source = highlight_string($source,true);

if ($r1 =='--') $source = preg_replace('#(&lt;\?.*?)(php)?(.*?&nbsp;)#s','\\1\\3',$source);

$source = preg_replace (array ( '/.*<code>\s*<span style="color: #000000">/', //
'#</span>\s*</code>#', // <code><span black>
$r1, $r2, // php tags
'/<span[^>]*><\/span>/' // empty spans
),'',$source);

if ($classes) $source = str_replace( array('style="color: #0000BB"','style="color: #007700"',
'style="color: #DD0000"','style="color: #FF8000"'),
array('class="phpdefault"','class="phpkeyword"',
'class="phpstring"','class="phpcomment"',),$source);

return $source;
}

echo '<p>Some tests:</p><p>';
echo php_highlight('<?php $test = new func("Text"); /* regular tags, use classes */ ?>',true),'<br />';
echo 'Inline code: ',php_highlight('<? $test = new func("Text"); /* short tags */ ?>'),
' works without or ',php_highlight('define (\'WITH_CLASSES\',\' too\'); /* no tags */',true),'<br />';
echo php_highlight('$test = new func("Text"); /* no tags, no classes */'),'<br />';
echo '</p><p>You are running PHP: '.phpversion().'</p>';

?>

hope it saves someones time, Tom
peter at int8 dot com
19-Apr-2006 11:43
This hasn't been mentioned, but it appears that PHP opening and closing tags are required to be part of the code snippet.
<?php highlight_string("<? \$var = 15; ?>"); ?>
works, while
<?php highlight_string("\$var = 15;"); ?>
does not. This is unforunate for those of use who want to show tiny code snippets, but there you go. Earlier versions of this function did not have this requirement, if I remember correctly.
m dot lebkowski+phpnet at gmail dot com
07-Apr-2006 11:31
stalker, I`m afraid your function has a bug. Whenever a input string will contain a substring: 'color="foo.bar"' it will be replaced by your function, whitch is of course incorrect. Try this:

<?php
function xhtmlHighlightString( $str, $return=false )
{
$hlt = highlight_string( $str, true );
$ret = str_replace(
array( '<font color="', '</font>' ),
array( '<span style="color: ', '</span>' ),
$hlt );
if($return)
return $ret;
echo $ret;
return true;
}

function xhtmlHilightFile( $path, $return = false )
{
return xhtmlHighlightString( file_get_contents( $path ), $return );
} ?>
stalker at ruun dot de
31-Dec-2005 09:37
to vouksh: I expanded your functions a bit:

<?php
function xhtmlHighlightString($str,$return=false) {
$hlt = highlight_string(stripslashes($str), true);
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
if($return)
return $ret;
echo $ret;
return true;
}
function xhtmlHighlightFile($path,$return=false) {
$hlt = highlight_file($path, true);
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
if($return)
return $ret;
echo $ret;
return true;
}
?>
05-Nov-2005 07:05
growling octopus's code didn't work under Windows, so I made this and it worked:
<?php
if (!empty($_GET['source'])) {
$f = file_get_contents($_SERVER['SCRIPT_FILENAME']);
highlight_string($f);
exit();
}
?>
growlingoctopus at no-spam dot gmail dot com
17-Oct-2005 11:37
Here's a trick I use when I want to show people the source to one of my scripts, but don't feel like uploading phps files or the host doesn't support them.
<?php
if (!empty($_GET['source'])) {
$f = implode(file(substr(__FILE__,strrpos(__FILE__,'/')+1)));
highlight_string(trim(substr($f,strpos($f,'?'.'>')+2)));
exit();
}
?>
By adding that to the top of the script, you can then call the script with ?source=1 and it will show the source for the file ... it should work with any script (as long as you aren't using $_GET['source'] for something else, you can always change that if you do).
vouksh at vouksh dot info
10-Sep-2005 05:27
Fully working, XHTML 1.1 ready xhtml_highlight function. I included the stripslashes, because of some problems I had with out it. It should be safe to leave it in there, but if you experience problems, feel free to take it out.

<?
function xhtml_highlight($str) {
$hlt = highlight_string(stripslashes($str), true);
$fon = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $hlt);
$ret = preg_replace('#color="(.*?)"#', 'style="color: \\1"', $fon);
echo $ret;
return true;
}
?>
webmaster at gelan dot org
20-Aug-2005 06:27
Some BB-codes width preg_replace:

<?php
function bb_url($str){
return preg_replace('#[URL=([^\']*)]([^\']*)[/URL]#', '<a href="\\1" target=_blank>\\2</a>', $str);
}
function bb_php($str){
$str = str_replace("]\n", "]", $str);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
return preg_replace($match, $replace, $str);
}
function bb_img($str){
return preg_replace('#[IMG]([^\']*)[/IMG]#', '<img src="\\1" />', $str);
}
function bb_b{$str){
return preg_replace('#([^\']*)', '<strong>\\1</strong>', $str);
}
function bb_i{$str){
return preg_replace('#([^\']*)', '<em>\\1</em>', $str);
}
function bb_parse{$str){
$str = bb_url($str);
$str = bb_php($str);
$str = bb_img($str);
$str = bb_b($str);
$str = bb_i($str);
return $str
}
?>
zer0
21-Jun-2005 04:18
Concerning my code below:

I'm sorry, I completely forgot about str_ireplace being for PHP 5 for some reason. Also, there was another error I missed (too many late nights ;)). Here's the corrected code:

<?php
function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
{
(string) $highlight = "";
if ( version_compare(PHP_VERSION, "4.2.0", "<") === 1 )
{
ob_start(); // start output buffering to capture contents of highlight
highlight_string($code);
$highlight = ob_get_contents(); // capture output
ob_end_clean(); // clear buffer cleanly
}
else
{
$highlight=highlight_string($code, true);
}

# Using preg_replace will allow PHP 4 in on the fun
if ( $inline === true )
$highlight=preg_replace("/<code>/i","<code class=\"inline\">",$highlight);
else
$highlight=preg_replace("/<code>/i","<code class=\"block\">",$highlight);

if ( $return === true )
{
return $highlight;
}
else
{
echo $highlight;
}
}
?>
zero
16-Jun-2005 10:55
In some cases, I found that it's useful to have highlight_string format <code>...</code> inline as part of a paragraph, and other times, as a block for demonstrating multiple lines of code. I made this function to help out.

<?php
function highlight_code($code, $inline=false, $return=false) // Pre php 4 support for capturing highlight
{
(string) $highlight = "";
if ( version_compare(phpversion(), "4.2.0", "<") === 1 )
{
ob_start(); // start output buffering to capture contents of highlight
highlight_string($code);
$highlight = ob_get_contents(); // capture output
ob_end_clean(); // clear buffer cleanly
}
else
{
$highlight=highlight_string($data, true);
}

## The classes below need to correspond to a stylesheet!
if ( $inline === true )
$highlight=str_ireplace("<code>","<code class=\"inline\">",$highlight);
else
$highlight=str_ireplace("<code>","<code class=\"block\">",$highlight);


if ( $return === true )
{
return $highlight;
}
else
{
echo $highlight;
}
}
?>
Sam Wilson
15-Jun-2005 06:32
manithu at fahr-zur-hoelle dot org forgot only one thing: to fix the break tags. The addidtion of the following should do it.

<?php
$str = str_replace("<br>", "<br />", $str);
?>
bpgordon at gmail dot com
13-Jun-2005 08:04
On dleavitt AT ucsc DOT edu's comment:

You might want to use md5($html_string) instead of "piggusmaloy" as a generally good programming practice. Just in case "piggusmaloy" is actually in $html_string.
dleavitt at ucsc dot edu
04-Jun-2005 09:37
This function does not seem to like <script> tags in HTML strings: if there are any close tags for scripts (whatever their language/type) the syntax highlighter will poop out. The workaround is simple though:
<?php
$html_string = str_replace("script","piggusmaloy", $html_string);
$html_string = highlight_string($html_string, true);
$html_string = str_replace("piggusmaloy","script", $html_string);
echo $html_string;
?>
This works best if you don't have "piggusmaloy" anywhere in your string (a safe assumption?)
trixsey at animania dot nu
29-May-2005 11:02
A neat function I made. Syntax coloring, row numbers, varying background colors per row in the table.

<?
function showCode($code) {
$html = highlight_string($code, true);
$html = str_replace("\n", "", $html);
$rows = explode("<br />", $html);

$row_num = array();
$i = 1;

foreach($rows as $row) {
if($i < 10) {
$i = "0".$i;
}

if($i==1) {
$row_num[] = "<tr><td><code><font color=\"#000000\"><code>$i</code></font>\t$row</code></td></tr>";
}

if($i!=1) {
if(is_int($i/2)) {
$row_num[] = "<tr bgcolor=\"#F9F9F9\"><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
} else {
$row_num[] = "<tr><td><code><font color=\"#000000\">$i</font>\t$row</code></td></tr>";
}
}

$i++;
}
return "<pre>\nFilename: <b>$_GET[file]</b>\n<table
style=\"border:1px #000000 solid\">".implode($row_num)."</table></pre>";
}
?>
support at superhp dot de
10-Apr-2005 11:58
With this function you can highlight php code with line numbers:

<?php
function highlight_php($string)
{
$Line = explode("\n",$string);

for($i=1;$i<=count($Line);$i++)
{
$line .= "&nbsp;".$i."&nbsp;<br>";
}

ob_start();
highlight_string($string);
$Code=ob_get_contents();
ob_end_clean();

$header='<table border="0" cellpadding="0" cellspacing="0" width="95%" style="border-style: solid; border-width:1px; border-color: white black black white">
<tr>
<td width="100%" colspan="2" style="border-style: solid; border-width:1px; border-color: white; background-color: #99ccff; font-family:Arial; color:white; font-weight:bold;">Php-Code:</td>
</tr>
<tr>
<td width="3%" valign="top" style="background-color: #99ccff; border-style: solid; border-width:1px; border-color: white;"><code>'.$line.'</code></td>
<td width="97%" valign="top" style="background-color: white;"><div style="white-space: nowrap; overflow: auto;"><code>';

$footer=$Code.'</div></code></td>
</tr>
</table>';

return $header.$footer;
} ?>
admin [at] develogix [dot] com
17-Feb-2005 07:15
I've been working on a good replacement for the highlight_string() function; and here is what I've come up with so far:

<?
function get_sourcecode_string($str, $return = false, $counting = true, $first_line_num = '1', $font_color = '#666'){
$str = highlight_string($str, TRUE);
$replace = array(
'<font' => '<span',
'color="' => 'style="color: ',
'</font>' => '</span>',
'<code>' => '',
'</code>' => '',
'<span style="color: #FF8000">' =>
'<span style="color: '.$font_color.'">'
);
foreach ($replace as $html => $xhtml){
$str = str_replace($html, $xhtml, $str);
}
// delete the first <span style="color:#000000;"> and the corresponding </span>
$str = substr($str, 30, -9);

$arr_html = explode('<br />', $str);
$total_lines = count($arr_html);
$out = '';
$line_counter = 0;
$last_line_num = $first_line_num + $total_lines;

foreach ($arr_html as $line){
$line = str_replace(chr(13), '', $line);
$current_line = $first_line_num + $line_counter;
if ($counting){
$out .= '<span style="color:'.$font_color.'">'
. str_repeat('&nbsp;', strlen($last_line_num) - strlen($current_line))
. $current_line
. ': </span>';
}
$out .= $line
. '<br />'."\n";
$line_counter++;
}
$out = '<code>'."\n".$out.'</code>."\n"';

if ($return){return $out;}
else {echo $out;}
}
?>

This function outputs valid XHTML 1.1 code by replacing font tags with span tags. You can also specify whether you want it to return or echo, output a line-count, the color of the line-count, and the starting line-count number.

Usage:
<?
// $str = string with php
// $return = true (return) / false (echo)
// default of false
// $counting = true (count) / false (don't count)
// default of true
// $start = starting count number
// default of '1'
// $color = count color with preceding #
// defalut of '#666'
get_sourcecode_string($str, $return, $counting, $start, $color);
?>
gaggge at gmail dot com
30-Jan-2005 04:26
This is a little function for highlighting bbcode-stylish PHP code from a mysql database.
(Like this: [php]<?php echo "test"; ?>[/php])

<?php
function bbcode($s)
{
$s = str_replace("]\n", "]", $s);
$match = array('#\[php\](.*?)\[\/php\]#se');
$replace = array("'<div>'.highlight_string(stripslashes('$1'), true).'</div>'");
return preg_replace($match, $replace, $s);
}
?>
admin at bwongar dot com
05-Jan-2005 11:11
I didn't get the expected results from the other XHTML_highlight function, so I developed my own and it is much more efficient. The older one uses a preg_replace to replace the contents of the tag to within a span tag. The only preg_replace in my function pulls the color attribute, and puts it within a str_replace'd span tag.

<?php
function xhtml_highlight($str) {
$str = highlight_string($str, true);
$str = str_replace(array('<font ', '</font>'), array('<span ', '</span>'), $str);
return preg_replace('#color="(.*?)"#', 'style="color: \\1"', $str);
}

?>
manithu at fahr-zur-hoelle dot org
06-Nov-2004 07:10
This function will return highlighted, xhtml 1.1 valid code (replaces <font> with <span> elements and color with style attributes):

<?php

function xhtml_highlight($str) {
$str = highlight_string($str, true);
//replace <code><font color=""></font></code>
$str = preg_replace('#<font color="([^\']*)">([^\']*)</font>#', '<span style="color: \\1">\\2</span>', $str);
//replace other <font> elements
return preg_replace('#<font color="([^\']*)">([^\']*)</font>#U', '<span style="color: \\1">\\2</span>', $str);
}

?>
mastah_br at yahoo dot com
12-Oct-2004 03:31
If you're looking for a more generic syntax highlighter, then you should see GeSHi Project, at http://qbnz.com/highlighter/
aidan at php dot net
26-Sep-2004 03:29
To add line numbers to source code, with optional function linking, use the below function:

http://aidanlister.com/repos/v/function.highlight_file_linenum.php

A much more thorough and smarter, though slower version is here:

http://aidanlister.com/repos/v/PHP_Highlight.php

  Ответить  
 
 автор: Commander   (26.08.2009 в 15:15)   письмо автору
 
   для: Вот случайно зашел   (26.08.2009 в 11:02)
 

Слуш, дружище, ты хотя бы теги для выделения кода используй, читать невозможно.

  Ответить  
 
 автор: cheops   (28.07.2009 в 11:28)   письмо автору
 
   для: sim5   (28.07.2009 в 04:08)
 

А эта... патчем поделитесь?

  Ответить  
 
 автор: psychomc   (28.07.2009 в 12:10)   письмо автору
 
   для: cheops   (28.07.2009 в 11:28)
 

:))

  Ответить  
 
 автор: ddhvvn   (28.07.2009 в 13:24)   письмо автору
 
   для: cheops   (28.07.2009 в 11:28)
 

Хе-хе!

Я думаю, поделиться ... )

  Ответить  
 
 автор: Trianon   (28.07.2009 в 13:54)   письмо автору
 
   для: ddhvvn   (28.07.2009 в 13:24)
 

>Я думаю, поделиться ... )

А у Вас тоже наработки есть?
поделитесь :)

Вот только что из этого выйдет в тираж...

  Ответить  
 
 автор: sim5   (28.07.2009 в 14:13)   письмо автору
 
   для: cheops   (28.07.2009 в 11:28)
 

Конечно выставлю. Сейчас поборю небольшой JS-сепаратизм самого быстрого браузера (FF, чтобы у него на лбу (панели инструментов) что-то выросло :))
Сейчас надо сделать подсветку РНР и JS. Я представляю себе это так:

а) функция cpp_highlight(), это основное тело, которое формирует строки кода, обрамляя их в элементы LI, а весь блок заключает в элемент OL. Собственно так сейчас все и работает, плюс делается небольшая подсветка. AlexSol нашел решение (эмперически высчитал :)) чтобы столбцы с номерами строк не "плавали", из чего были получены усредненные выражения для стиля OL, и теперь в этой части все ОК.
б) посредством callback или просто функцией принимающей в качестве параметра строку, обрабатывать ее. Обработка ничинается с проверки многострочных выражений - комментария заключенного в /* */ и выражения заключенного в кавычки.... Если таковое присутствует и строка не закончена, то возвращает обработанную строку как незаконченную с симоволом-признаком которым она должна закрываться (*/ или кавычка соответствующая). Основное тело не найдя в следующей строке это символа признака, просто соответствующее ее подсвечивает. Если находит его, передает опять строку функции обработчику.
в) функции, выражения, операторы - это массив, элементами которого будет заменяться соответствующее выражение в строке, но с обязательной проверкой того, заключено ли оно в комментарий или нет.

В общем вот так я себе вижу это. Вот такую функцию обработчик можно было бы коллективно написать, или принять участие в написании :)

  Ответить  
 
 автор: sim5   (08.08.2009 в 06:11)   письмо автору
15.4 Кб
 
   для: sim5   (28.07.2009 в 04:08)
 

И так.... В прикреплении архив с примером того, как будет выглядеть форма с элементами втавки ВВ-тегов. К выше изложенному добавлю только то, что добавлена вставка табличных данных, что иногда необходимо, и панель символов для их вставки. В общем смотрите, щелкайте, предлагайте....

Чуть позже прикреплю архив файлов из состава liteforum, которые подверглись изменению и те, что добавлены. Сразу оговорюсь, что оформление рассматривалось только по отношению к базовому стилю, папка aggression, а таже администрирование не рассматиривались.

Сейчас можно начинать работать над подсветкой кода.

  Ответить  
 
 автор: Незнайка   (08.08.2009 в 11:18)   письмо автору
 
   для: sim5   (08.08.2009 в 06:11)
 

Оригинально сделано :)

  Ответить  
 
 автор: sim5   (08.08.2009 в 12:09)   письмо автору
 
   для: Незнайка   (08.08.2009 в 11:18)
 

Оригинальностью пусть верстальщики займутся, их тут, на форуме, мнооооого шастает :) Моя задача посеять зерно ;-)

  Ответить  
 
 автор: cheops   (09.08.2009 в 13:17)   письмо автору
 
   для: sim5   (08.08.2009 в 06:11)
 

Взял на исследование.

  Ответить  
 
 автор: Trianon   (10.08.2009 в 21:55)   письмо автору
 
   для: cheops   (09.08.2009 в 13:17)
 

Крайне интересен вердикт.
Интересен также вердикт по родственной теме.

  Ответить  
 
 автор: sim5   (11.08.2009 в 16:17)   письмо автору
32.7 Кб
 
   для: cheops   (09.08.2009 в 13:17)
 

Просьба - проверить вложение. Это окончательный вариант, который я уже встраиваю в скрипты, но.... Я проверяю у себя под: Opera 9.64, FF 3.5.2, Safari 4.0.2, IE 8. Все работает, но вот попросил одного из форумчан посмотреть у себя - заключение, в FF не работает вставка ВВ-тегов, курсор после вставки убегает постоянно в конец строки, ошибки доступа к элементам, типа getElementById и т.п....
Посмотрите, действительно ли это так? На каких из двую страниц не работает что-то и каких версиях браузеров?

  Ответить  
 
 автор: Commander   (12.08.2009 в 17:51)   письмо автору
 
   для: sim5   (11.08.2009 в 16:17)
 

>заключение, в FF не работает вставка ВВ-тегов...

DeepPark 1.6a1 - все нормально, кроме кнопки курсива.

P.S. Кстати, классно вышло. Sim5, большой вам респект. Мастер, что уж тут сказать.

  Ответить  
 
 автор: sim5   (12.08.2009 в 18:00)   письмо автору
 
   для: Commander   (12.08.2009 в 17:51)
 

А что с кнопкой курсива?

  Ответить  
 
 автор: sim5   (23.08.2009 в 21:42)   письмо автору
141.5 Кб
 
   для: sim5   (28.07.2009 в 04:08)
 

В прикреплении архив измененных файлов (большая часть, это небольшая "косметика") и добавленных. Файлы архива вложены в папки согласно liteforum50, кроме двух папок - js и images. Все места в файлах, в которых есть изменения или добавления, помечены комментариями в верхнем регистре ДОБАВЛЕНО, ИЗМЕНЕНО (для "не промахнуться :)). Есть отметка об изменении и как HTML комментарий, в файле menu.php - в нем указана ссылка на несуществующий файл.

Все js-сценарии ранее существовавшие в файлах liteforum50, удалены из них. JS-сценарии подключаемые, их два - один для админ раздела, и второй для форума (обслуживание форм). Папка js содержит по две копии каждого файла - один сжатый, второй исходник. Подключаются сжатые файлы. Также в отдельную папку выделены изображения общие для всех оформлений, это иконки, смайлы.

Смайлы подключаются не за счет наличия папки smiles в папке скинов, а установкой чекбокса в настройках форума. Для этого в таблицу liteforum_setting добавлено поле smiles (enum), и соответствующий чекбокс в settings.php. В этот же файл встроен IFRAME, в котором независимо от остальных настроек форума, происходит редактирование таблицы символов подключаемым файлом utils.sumbols.php. Символы содержатся в файле sumbols.arr как сериализованный массив.

В таблицу liteforum_posts добавлены два поля: doc_name и doc_ico. Первое хранит оригинальное имя загруженного на сервер файла, а второе его расширение. doc_name определяет текст атрибута alt избражения иконки, doc_ico иконку, которая будет выводиться в сообщении. Графические файлы и файлы с расширением .txt выводятся как и ранее в браузер, все остальные отдаются на скачивание через добавленный скрипт с именем хранящимся в doc_name.

Пришлось проверять добавления и под скином aggression, и оказалось, что.... В общем вновь добавляемые изображения приготовлены и для этого скина. Самая большая трудность, это стили. Стиль read.css не используется вообще, его содержимое перенесено в стиль forum.css. Все необходимое для обслуживания форм содержит стиль action.css, стиль подсветки кода вынесен в файл - lihtcode.css. Подключение необходимых стилей задается в основном скрипте, типа addpost.php, addtheme.php и т.д., как массив для topforumaction.php.
Но стили проверены и просмотрены не полностью. Например, создание персонального сообщения показало, что в базу не сохраняется тема поста, к тому же пост по умолчанию скрыт. Если в режиме администрирования разрешить вывод этого поста, добавив название темы, то при обращении к ней происходит ошибка. Есть еще ошибки, которые не позволили (пока) проверить все. Но основное проверено.

В файле utils.posts.php еще необходимо добавление обработки ВВ-кода таблицы пользователя (при необходимости), ну и главное - написать подсветку кода. На данный момент, она та, что и использовалась для пробы, при разработке вывода кода с нумерацией.

Пока все, вроде бы ничего не забыл....

PS. Забыл все таки включить в архив два файла, исправлено. )

  Ответить  
 
 автор: sim5   (26.08.2009 в 10:33)   письмо автору
6.5 Кб
 
   для: sim5   (28.07.2009 в 04:08)
 

Немного доработанный скрипт редактирования таблицы символов. После детального просмотра оказалось, что логика проверки и отправки формы не совсем корректа. Изменено - так как настройки, это администратор, то все проверки формы произодятся на клиенте (JS), из РНР скрипта они удалены.

  Ответить  
Rambler's Top100
вверх

Rambler's Top100 Яндекс.Метрика Яндекс цитирования