Can't get str_replace() to strip out spaces in a PHP string
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
Paul Elliot
Updated on June 09, 2022Comments
-
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 about 11 years
trim()
will only remove whitespace from the start and end of the string -
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 about 11 yearsI 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 about 11 yearsuse " ". the_sub_field('venue_title')."" or maybe ""+the_sub_field('venue_title')+""
-
JackSD over 10 yearsThis is the correct answer to this threat and needs to be marked so
-
Artur Czyżewski over 7 yearsSame here. String was retrived from Wordpress meta field. Was saved in admin panel, after "copy-paste" from old site, with different encoding...
-
Martin over 7 yearsTry substituting the
\s+
for\h+
for horizontal whitespace, this will retain line breaks, if needed. -
Adrien G about 4 yearsyou are the real mvp
-
Thanasis about 2 yearsThat did the trick