PHP Stringhe /2

Continuiamo a lavorare sulle stringhe.

La str_replace() permette di modificare una stringa (subject) sostituendo un dato valore (replace) al posto di una specificata substringa (search). Esiste anche una versione case insensitive, str_ireplace(), che opera la sostituzione senza badare a maiuscole o minuscole:

$input = "Prova, prova ... PROVA!";
echo "Input: \"$input\"<br />";

$output = str_replace("prova", "test", $input);
echo "Ouput: \"$output\"<br />";

$output = str_ireplace("prova", "test", $input);
echo "Ouput: \"$output\"<br />";

Se vogliamo lavorare con stringhe con una lunghezza minima garantita, possiamo usare la str_pad() per aggiungere alla riga, se più corta, caratteri riempitivi. Di default sono aggiunti spazi bianchi alla destra:

$input = "Hi";
echo "[", str_pad($input, 6), "]<br />";
echo "[", str_pad($input, 6, "-", STR_PAD_LEFT), "]<br />";
echo "[", str_pad($input, 6, "_", STR_PAD_BOTH), "]<br />";

E' possibile creare una stringa multiplo di una data, usando str_repeat:

echo str_repeat("echo... ", 4);

Per convertire una stringa in un array usiamo la str_split():

$input = "This is a string";
echo "The input was \"$input\"<br />";

$output = str_split($input);
echo "The output is: ";
$size = count($output);
for($i = 0; $i < $size; ++$i)
echo "[", $output[$i], "] ";

Per estrarre substringhe sapendo l'offset e la lunghezza di quanto si vuole estrarre, si può usare la substr(), che può essere usata anche a partire dal fondo della stringa (indicando un offset negativo). Nota che se non viene specificata la lunghezza della sottostringa, si assume che si voglia arrivare a fine stringa:

$input = "This is a string";
echo "The input was \"$input\"<br />";

echo substr($input, 0, 4), "*";
echo substr($input, 5, 2), "*";
echo substr($input, -6), "*";
echo substr($input, -8, 1);

Per convertire una stringa a tutto maiuscolo o tutto minuscolo si possono usare strtolower() e strtoupper():

$input = "This Is a String";
echo "Given this string \"$input\":<br />";

echo "tolower: ", strtolower($input), "<br />";
echo "toupper: ", strtoupper($input), "<br />";

Si può usare la sscanf() per estrarre delle sottostringhe secondo una particolare formattazione - vedi la printf/scanf del linguaggio C:

$date = "12 May 2009";
list($day, $month, $year) = sscanf($date, "%d %s %d");
echo "Day: $day, month: $month, year: $year.<br />";

Per vedere questi script php in azione vedi qui.

Nessun commento:

Posta un commento