PDA

View Full Version : [php] sostituire parti di una stringa


AlexCyber
10-04-2007, 20:42
ho una stringa cosi fatta:

$str = "<p>testo testo testo</p><code><?php echo 'codice php'; ?></code><p>testo testo testo</p>"

avrei bisogno di formattare la parte allì'interno dei tag code con la funzione htmlentities avete qualche suggerimento?

grazie?:help:

kk3z
10-04-2007, 21:44
<?php
$str = "<p>testo testo testo</p><code>".htmlentities("<?php echo 'codice php'; ?>")."</code><p>testo testo testo</p>";
?>

AlexCyber
10-04-2007, 21:47
il problema e che la stringa viene generata dinamicamente e quindi non so a priori dove si trova la parte di stringa da formattare...:rolleyes:

kk3z
10-04-2007, 22:23
<?

function htmlentities_callback($match)
{
return htmlentities($match[1]);
}

$str = "<p>testo testo testo</p><code><?php echo 'codice php'; ?></code><p>testo testo testo</p><code><?php echo 'codice php'; ?></code>";
echo preg_replace_callback("|<code>(.+?)</code>|", "htmlentities_callback", $str);

?>

output:
<p>testo testo testo</p>&lt;?php echo 'codice php'; ?&gt;<p>testo testo testo</p>&lt;?php echo 'codice php'; ?&gt;

AlexCyber
10-04-2007, 22:35
grazie x lo script che mi hai postato, e se volessi mantenere in output anche <code>.... ?

<p>testo testo testo</p><code>&lt;?php echo 'codice php'; ?&gt;</code><p>testo testo testo</p>

ps: nel pattern della regEx hai scritto (.+?) cosa significa?

....abbi pazienza sono un niubbi...

kk3z
10-04-2007, 22:49
Ops in effetti...
function htmlentities_callback($match)
{
return "<code>".htmlentities($match[1])."</code>";
}

ps: nel pattern della regEx hai scritto (.+?) cosa significa?
Qui ci vorrebbe andbin e le sue super spiegazioni... prova a guardare questa guida (http://www.regular-expressions.info/repeat.html), da "Watch Out for The Greediness!" in poi. In poche parole, l'operatore + è "greedy", e aggiungendo il ? diventa "lazy". Prova a fare una ricerca in questo forum per i post di andbin e la parola chiave "greedy".

AlexCyber
10-04-2007, 22:56
grazie x la disponibilità

sto testando il codice, ma ho ei problemi quando la stringa è formata da più righe, poi ho provato anche cosi

function htmlentities_callback($match)
{
return htmlentities($match[1]);
}

$str = "<p>testo testo testo</p><p class='codice'><?php echo 'codice php'; ?></p><p>testo testo testo</p><p class='codice'><?php echo 'codice php'; ?></p>";
echo preg_replace_callback("|<code>(.+?)</code>|", "htmlentities_callback", $str);

usando <p class='codice'> al posto di code ma niente da fare....