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

14,974

Solution 1

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

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

Solution 2

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 )

Solution 3

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

Try

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

Solution 4

use trim like this

TRIM($fieldname);

EDIT:

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

Solution 5

The issue was the field that it was pulling, not the rest of the php. 'the_sub_field('venue_title')' pulls a field from the wordpress plugin 'Advanced Custom Fields' but this function is intended to display the data rather than just retrieve it. Instead i used 'get_sub_field('venue_title')' and it worked. cheers for the help

Share:
14,974
Paul Elliot
Author by

Paul Elliot

Updated on June 09, 2022

Comments

  • Paul Elliot
    Paul Elliot about 2 years

    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 still with the spaces in it.

       <?php
         $fieldname = the_sub_field('venue_title');
         $classname = str_replace(' ', '', $fieldname);
         echo $classname;
       ?>
    
  • billyonecan
    billyonecan about 11 years
    trim() will only remove whitespace from the start and end of the string
  • ty812
    ty812 about 11 years
    'trim()' only trims at the beginning or the end of a string. In Paul's example, whitespace characters might be within the string.
  • Paul Elliot
    Paul Elliot about 11 years
    I think the issue is that the string is not getting treated as a string. it needs a " on either side. how would you do this in php? eg $fieldname = "'" . the_sub_field('venue_title') . "'";
  • Blu
    Blu about 11 years
    use " ". the_sub_field('venue_title')."" or maybe ""+the_sub_field('venue_title')+""
  • JackSD
    JackSD over 10 years
    This is the correct answer to this threat and needs to be marked so
  • Artur Czyżewski
    Artur Czyżewski over 7 years
    Same here. String was retrived from Wordpress meta field. Was saved in admin panel, after "copy-paste" from old site, with different encoding...
  • Martin
    Martin over 7 years
    Try substituting the \s+ for \h+ for horizontal whitespace, this will retain line breaks, if needed.
  • Adrien G
    Adrien G about 4 years
    you are the real mvp
  • Thanasis
    Thanasis about 2 years
    That did the trick