问题
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;
?>
回答1:
Try to add u-parameter for regex-pattern, because a string can have UTF-8 encoding:
$classname = preg_replace('/\s+/u', '', $fieldname);
回答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 )
回答3:
The problem might be the character not being a space, but another whitespace character.
Try
$classname = preg_replace('/\s/', '', $fieldname);
回答4:
use trim like this
TRIM($fieldname);
EDIT:
preg_replace('/\s+/', '', $fieldname);
回答5:
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.
回答6:
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
回答7:
<?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')
;
来源:https://stackoverflow.com/questions/16563421/cant-get-str-replace-to-strip-out-spaces-in-a-php-string