Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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;
   ?>
like image 720
Paul Elliot Avatar asked May 15 '13 11:05

Paul Elliot


People also ask

How do I strip whitespace in PHP?

The trim() function removes whitespace and other predefined characters from both sides of a string. Related functions: ltrim() - Removes whitespace or other predefined characters from the left side of a string.

How do I strip all spaces from a string?

Use the String. replace() method to remove all whitespace from a string, e.g. str. replace(/\s/g, '') . The replace() method will remove all whitespace characters by replacing them with an empty string.

How do I remove a word from a string in PHP?

Answer: Use the PHP str_replace() function You can use the PHP str_replace() function to replace all the occurrences of a word within a string.

How can I replace multiple characters in a string in PHP?

Approach 1: Using the str_replace() and str_split() functions in PHP. The str_replace() function is used to replace multiple characters in a string and it takes in three parameters. The first parameter is the array of characters to replace.


1 Answers

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

$classname  =  preg_replace('/\s+/u', '', $fieldname);
like image 191
Alekzander Avatar answered Sep 21 '22 16:09

Alekzander