PHP: Whitespaces

Array ( [0] => [1] => [2] => blue [3] => [4] => [5] => [6] => [7] => car [8] => [9] => [10] => red [11] => [12] => [13] => elder [14] => [15] => green [16] => watch )

blue car red elder green watch

Array ( [0] => [1] => blue [2] => car [3] => red [4] => elder [5] => green [6] => watch )

1


The code used for index.php is below:


<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <link rel="stylesheet" href="../styles.css">
    <title>PHP: Whitespaces</title>
</head>
<body>
    <h1 class="lesson-h1">PHP: Whitespaces</h1>
        
    <?php
        //this can come out messy because of whitespaces
        $string = "  blue     car   red   elder  green watch";
        $keywords = explode(' ', $string);

        print_r($keywords);

        //To fix this we will use trim()
        $trimmed = trim($string, ' ');
        echo "<p>$trimmed</p>";

        //This also corrects it by using preg_split()
        $trimmed2 = preg_split('/[\s]+/', $string);
        echo "<p>" . print_r($trimmed2) . "</p>";

        include('../show_code.php');
        show_code('index.php');
    ?>

</body>
</html>