Paul Elliot
Paul Elliot

Reputation: 475

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;
   ?>

Upvotes: 14

Views: 16899

Answers (7)

Blu
Blu

Reputation: 4056

<?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');

Upvotes: 0

Alekzander
Alekzander

Reputation: 956

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

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

Upvotes: 38

Paul Elliot
Paul Elliot

Reputation: 475

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

Upvotes: 2

Amir
Amir

Reputation: 4111

use trim like this

TRIM($fieldname);

EDIT:

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

Upvotes: 3

user1908308
user1908308

Reputation:

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.

Upvotes: 2

Vijaya Pandey
Vijaya Pandey

Reputation: 4282

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 )

Upvotes: 16

ty812
ty812

Reputation: 3323

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

Try

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

Upvotes: 5

Related Questions