Jump to content

[SOLVED] Replace Multiple Spaces With One Space


papaface

Recommended Posts

Hello,

 

I am trying to search a string for a particular occurrence however I want it to work regardless of spaces.

 

This is the code I have currently:

   $string = "Hello I am papa_face.";

   $pos = strpos($string, "I am papa_face");
   if ($pos !== false)
      echo "Contains the string.";
      else
      echo "Does NOT contain the string.";

Obviously in this example the string does contain the search term so it returns "Contains the string."

 

However if I change the string to:

   $string = "Hello I am                 papa_face.";

   $pos = strpos($string, "I am papa_face");
   if ($pos !== false)
      echo "Contains the string.";
      else
      echo "Does NOT contain the string.";

The string is not found. How can I get around this?

As you stated in the subject of this topic, you can replace white space. You could try completely removing white space in both strings with something like this:

 

$string = str_replace(' ', '', $string);
//or with regex maybe?
$string = preg_replace('/\s/', '', $string);

Archived

This topic is now archived and is closed to further replies.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.