PHP trim() not doing what it's supposed to do

Discussion in 'PHP' started by PoPSiCLe, Feb 21, 2016.

  1. #1
    Okay, I have a parsed string (a line-fragment from a text), that for some reason have a lot of whitespace - one should think trim() would fix that, but for some reason, it doesn't work.

    Here's the relevant part of the code:
    
    foreach($getfile as $line) {
      if (strstr($line, 'h4')) {
      $get_link_id = str_replace('"','',strstr(strstr($line,'"'),'">',true));
      $digit = explode('. ',$line)[0];
      var_dump($digit); //this outputs that the $digit-variable is 19 characters, instead of 1 or 2
      // echo sprintf("%02d", trim($digit)); //this doesn't work, since the string is way too long, and trim() doesn't work - I've tried running trim() outside the sprintf as well
      echo '<li><a href="#'.$get_link_id.'">'.strip_tags($line).'</a></li>';
      }
    }
    
    Code (markup):
    I would think that trim() should fix this, but it doesn't, and I'm a bit confused... anyone have any idea what I can do?
     
    PoPSiCLe, Feb 21, 2016 IP
  2. sarahk

    sarahk iTamer Staff

    Messages:
    28,875
    Likes Received:
    4,547
    Best Answers:
    123
    Trophy Points:
    665
    #2
    Huh, fell foul of this a few weeks ago. Can't remember what I did in the end but basically worked around it.
     
    sarahk, Feb 21, 2016 IP
  3. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #3
    Yeah... I can probably hack together something that will get rid of the problem, but I would much prefer to fix the underlying issue :)
     
    PoPSiCLe, Feb 21, 2016 IP
  4. PoPSiCLe

    PoPSiCLe Illustrious Member

    Messages:
    4,623
    Likes Received:
    725
    Best Answers:
    152
    Trophy Points:
    470
    #4
    And... I figured it out. It was due to not stripping tags before trying to do the padding.
    Ended up changing it to this:
    
      if (strstr($line, 'h4')) {
      $get_link_id = str_replace('"','',strstr(strstr($line,'"'),'">',true));
      $digit = explode('. ',strip_tags($line));
      $digit[0] = str_replace(" ", "&nbsp;&nbsp;", str_pad($digit[0], 2, " ", STR_PAD_LEFT));
      echo '<li><a href="#'.$get_link_id.'">'.$digit[0].'. '.$digit[1].'</a></li>';
      }
    
    PHP:
     
    PoPSiCLe, Feb 21, 2016 IP