Can't get str_replace() to strip out spaces in a PHP string

前端 未结 7 1006
谎友^
谎友^ 2020-12-14 23:54

Hi, I am getting a PHP string which I need to strip the spaces out of. I have used the following code but when I echo $classname it just displays the string sti

相关标签:
7条回答
  • 2020-12-14 23:59

    The problem might be the character not being a space, but another whitespace character.

    Try

    $classname = preg_replace('/\s/', '', $fieldname);
    
    0 讨论(0)
  • 2020-12-15 00:03

    use trim like this

    TRIM($fieldname);
    

    EDIT:

    preg_replace('/\s+/', '', $fieldname);
    
    0 讨论(0)
  • 2020-12-15 00:05

    Try to add u-parameter for regex-pattern, because a string can have UTF-8 encoding:

    $classname  =  preg_replace('/\s+/u', '', $fieldname);
    
    0 讨论(0)
  • 2020-12-15 00:08

    It could be that the space is not really a space, but other form of whitesspace.

    You might want to try:

    $classname = preg_replace('/\s+/', '', $fieldname);
    

    From here.

    0 讨论(0)
  • 2020-12-15 00:18

    If you know the white space is only due to spaces, you can use:

    $classname = str_replace(' ','',$fieldname ); 
    

    But if it could be due to space, you can use:

    $classname = preg_replace('/\s+/','',$fieldname )
    
    0 讨论(0)
  • 2020-12-15 00:20
    <?php
      $fieldname = "I  am  21  Years  Old";
      $classname = str_replace(' ', '', $fieldname);
      echo $classname;
    ?>
    

    This runs perfectly. Check value return by this function: the_sub_field('venue_title');

    0 讨论(0)
提交回复
热议问题