MANUAL DE PHP

(y algo mas)windsurf pozo izquierdo
Google
search for in the  
ELMARRAJO.COM mysql bulma desarrollo web linux fedora html ayuda

windsurf mercedes camper

highlight_string

(PHP 4, PHP 5)

highlight_string -- Resaltado de sintaxis de una cadena

Descripción

mixed highlight_string ( string cadena [, bool devolver] )

La función highlight_string() imprime una versión con resaltado de código de cadena usando los colores definidos en el resaltador de código incorporado de PHP.

Si el segundo parámetro devolver es definido a TRUE entonces highlight_string() devolverá el código resaltado como una cadena en lugar de imprimirlo. Si el segundo parámetro no es definido a TRUE entonces highlight_string() devolverá TRUE de tener éxito, o FALSE en caso de fallo.

Ejemplo 1. Ejemplo de highlight_string()

<?php
highlight_string
('<?php phpinfo(); ?>');
?>

El anterior ejemplo producirá la siguiente salida (en PHP 4):

<code><font color="#000000">
<font color="#0000BB">&lt;?php phpinfo</font><font color="#007700">();
</font><\font color="#0000BB">?&gt;</font>
</font>
</code>

El anterior ejemplo producirá la siguiente salida (en 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>

Nota: El parámetro devolver apareció en PHP 4.2.0. Antes de esta versión, su comportamiento era el predeterminado, el cual es FALSE.

Vea también highlight_file().



add a note add a note User Contributed Notes
highlight_string
thomas et luegger _dot_ de
20-Jul-2006 05: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 04: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 04: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 01: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 11: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 04: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 10: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 11: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('#[B]([^\']*)[/B]', '<strong>\\1</strong>', $str);
}
function
bb_i{$str){
return
preg_replace('#[I]([^\']*)[/I]', '<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
20-Jun-2005 09: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 03: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
14-Jun-2005 11: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 01: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 02: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 04: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 04: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
16-Feb-2005 11: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 08: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 03: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 11: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
11-Oct-2004 08: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 08:29
To add line numbers to source code, with optional function linking, use the below function:

http://aidan.dotgeek.org/lib/?file=function.highlight_file_linenum.php

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

http://aidan.dotgeek.org/lib/?file=PHP_Highlight.php

Citas célebres

Amor: una serpiente con dos cabezas que se vigilan sin cesar.

Elias Canetti
Escritor búlgaro
Citas en tu mail
©Contenidos Gratis

Ilusiones Opticas
ilusion_optica_027.jpg
Contenidos Web

Chiste de... Médicos
Tartamudo parcial

El psicologo a un paciente:

- ¿Y tartamudea usted todo el tiempo?

- No, solo cuando hablo.
Chistes en tu mail
©ContenidosGratis

Humor Gráfico
humor_grafico_030.jpg
Contenidos Web

Inicio | Acción | Estrategia | Palabras | Puzzles | Solitarios | Foro Trucos
Cake ManiaCake Mania
Jugadores: 6835
Categoría del juego: Acción
Objetivo del juego: Ayuda a Jill a recuperar la pastelería de su abuela llevando su propia pastelería; consigue clientes y gana dinero.
Rainbow WebRainbow Web
Jugadores: 2199
Categoría del juego: Puzzles
Objetivo del juego: Rompe un pegajoso hechizo y salva un reino de fantasía en Rainbow Web. Tendrás toneladas de diversión mientras juegas a este mágico desafío para la mente.
Mahjongg FortunaMahjongg Fortuna
Jugadores: 12462
Categoría del juego: Solitarios
Objetivo del juego: Velocidad y habilidad mental son las armas más importantes en esta versión de un antiguo juego asiático. Despeja el tablero lo antes posible haciendo clic en las fichas iguales y gánate la fama eterna de la puntuación más alta.
Chainz 2Chainz 2
Jugadores: 6955
Categoría del juego: Puzzles
Objetivo del juego: Entra en el mundo de las combinaciones con Chainz 2: Relinked, emocionante secuela del exitazo del año pasado, Chainz. Gira eslabones y crea combinaciones de 3 ó más.
DeliciousDelicious
Jugadores: 4405
Categoría del juego: Acción
Objetivo del juego: ¿Eres un as de la multitarea? ¿Quieres que tus clientes estén contentos? ¡Pues Delicious es tu juego! Sacia el apetito de los clientes y tenlos contentos; ¡no te arriesgues!
BookwormBookworm
Jugadores: 4568
Categoría del juego: Palabras
Objetivo del juego: Junta las letras para formar palabras. ¡Las palabras más largas valen más puntos!
ZumaZuma
Jugadores: 4976
Categoría del juego: Acción
Objetivo del juego: Controla el ídolo de la rana de piedra de los antiguos Zuma en este intrigante enigma de acción. ¡Dispara bolas para formar conjuntos de tres, pero si dejas que lleguen a la calavera dorada morirás!
Jewel of AtlantisJewel of Atlantis
Jugadores: 3798
Categoría del juego: Puzzles
Objetivo del juego: Descubre la ciudad hundida de la Atlántida y busca valiosos tesoros. Viaja más allá de las profundidades del mar y vive trepidantes aventuras en Jewel of Atlantis.
Jewel QuestJewel Quest
Jugadores: 3727
Categoría del juego: Puzzles
Objetivo del juego: Convierte la arena de la antigua selva en oro tan rápido como puedas juntando grupos de 3 elementos. ¡Los grupos más grandes valen más puntos!
Bejeweled 2Bejeweled 2
Jugadores: 3659
Categoría del juego: Puzzles
Objetivo del juego: Con cuatro modos de juego únicos y fascinantes, nuevas piezas de juego explosivas e imponentes fondos planetarios, Bejeweled 2 es mucho más adictivo que nunca.
Contenidos gratis en tu webSiguiente >>

Fotos divertidas
fotos_increibles_0219.jpg
Contenidos Web
microrobots avion deportes riesgo recetas cocina canaria juegos online gratis moto motociclismo horoscopos naranjas valencianas surf canarias montañismo ciudades turismo postales gratis library Horoscopos Diarios Windsurf Canarias
fregadero microondas placa electrica bañopreparar camper pantalla plananevera compresor electricacamper fiat ducato camper baño quimicomampara enrollable bañocamper aire climatizadofurgoneta surf windsurffurgoneta surf windsurftelevisor furgonetas camperfurgonetas camper cama

Sudoku del día
Nivel de dificultad: Fácil



Cómo jugar:
El juego consiste en colocar los números del 1 al nueve de tal forma que no se repita el mismo número en la columna, fila y caja (bloques 3x3 enmarcados).

©Contenidos Gratis | Sudoku en tu mail
Sucedió el...

30 de agosto de 1617

Fallece Santa Rosa de Lima, por la que se celebra el "Día de la Patrona de América".
Efemérides en tu mail
©Contenidos Gratis
windsurf canarias youtube porno canarias baleares valencia madrid fallera mayor campus party alcacer feria valencia fernando alonso loterias dinero inversiones violencia de genero makro empresas cartera soledad tolerancia metro valencia gobierno de españa violencia de genero UIMP navidad