L2 Info : PHP et Programmation Web
 
◃  Ch. 1 Le language PHP  ▹
 

Opérations courantes sur les chaînes

  • Concaténation avec l'opérateur . ou la fonction implode
    $variable1 = 'Professeur';
    $variable2 = 'Dumbledore';
    $chaines1 = $variable1 . ' ' . $variable2;
    $chaines2 = implode(array(" Albus", ' Percival', "Wulfric"));
    $chaines3 = implode(' ; ',array(" Albus", ' Percival', "Wulfric"));
    echo implode(array("<p>",$chaines1,"<br />", $chaines2,"<br />",$chaines3,"</p>"));
    $implodeCh = implode(array("<p>",$chaines1,"<br />", $chaines2,"<br />",$chaines3,"</p>"));
    
    Résultat :

    Professeur Dumbledore
    AlbusPercivalWulfric
    Albus ; Percival ; Wulfric

  • Découpage d'une chaîne avec la fonction explode
    $stringArray = explode(';', $chaines3);
    foreach($stringArray as $ch) {
       echo "*".$ch."*"; // pas de traitement des espaces
       }
    echo "<br />";
    foreach($stringArray as $ch) {
       echo "*".trim($ch)."*"; // suppression des espaces en début et fin de chaine
    }
    
    Résultat :
    *Albus ** Percival ** Wulfric*
    *Albus**Percival**Wulfric*
  • À voir aussi strlen, strpos, substr, str_replace, str_rot13, ...