Search code examples
phpwhitespaceremoving-whitespace

PHP remove whitespaces - "ghost" lines appear


I have an HTML Form that queries entries from a MySQL Database and inputs these values into several text areas where they may be edited and these changes subsequently saved.

The SQL/PHP interaction seems to work find, I get the queried information and am able to update the database accordingly. However, whenever I access the (string) information and echo this into the text area, there are suddenly four blank lines inserted from nowhere in front of the actual string content.

I do not understand where these blank lines are coming from and moreover how to get rid of them.

Here's the code from the form text area:

<textarea 
    name="MicroLoc_Entry" 
    id="MicroLoc_Entry" 
    style="position:absolute;left:581px;top:45px;width:73px;height:18px;z-index:14;" 
    rows="1" 
    cols="1" 
    spellcheck="false"
>
    <?php 
        include ('db_connect.php'); 
        $ID = $_POST['ItemID']; 
        $sql = "SELECT MicroLoc from Main WHERE ItemID = ".$ID ; 
        $result = mysqli_query($link, $sql); 
        $res = mysqli_fetch_array($result);  
        $msg = $res['MicroLoc'];
        echo preg_replace('/\s\s+/', '', $msg); 
    ?>
</textarea>

Using either ltrim($string) or preg_replace('/\s+/g', '', $string) or preg_replace('/\s\s+/', '', $string) does only reduce the whitespace to two additional blank lines but does not remove them all.

Thanks a lot for any help!


Solution

  • Run your code before the <textarea> and then echo the result inside <textarea>. So, if your code generate any newlines - it will be outside <textarea>.

    <?php 
            include ('db_connect.php'); 
            $ID = $_POST['ItemID']; 
            $sql = "SELECT MicroLoc from Main WHERE ItemID = ".intval($ID) ; 
            $result = mysqli_query($link, $sql); 
            $res = mysqli_fetch_array($result);  
            $msg = $res['MicroLoc'];
            $echomsg = preg_replace('/\s\s+/', '', $msg); 
    ?>
    <textarea 
        name="MicroLoc_Entry" 
        id="MicroLoc_Entry" 
        style="position:absolute;left:581px;top:45px;width:73px;height:18px;z-index:14;" 
        rows="1" 
        cols="1" 
        spellcheck="false"
    ><?php echo $echomsg; ?></textarea>
    

    Also please be sure, that there is no any other spaces or newlines between the <textarea> and </textarea> tags. Because these also can be the source of unwanted symbols.