0

Consider This string that has wrong spacing:

$q1 = '   little  cute girl';

(3 at the beginning, it should be no space) (2 between 'little' and 'cute', it should be 1)

If I explode and print_r,

$r1 = explode(' ', $q1);
print_r($r1);

The output will be:

Array ( [0] => [1] => [2] => [3] => little [4] => [5] => cute [6] => girl ) 

What can I do so that $q1 can be properly spaced,

$q1_after_correction = 'little cute girl'

so that after explode and print_r, the output to be like this: (No space at beginning!)

Array ( [0] => little [1] => cute [2] => girl )

Any idea please?

Newbee123
  • 61
  • 6

1 Answers1

1

try this

$q1 = '   little  cute girl';
$spaceCleanUp = preg_replace('/\s/', ' ', $q1); // This will replace successive spaces with one
$r1 = explode(' ', $spaceCleanUp);
print_r($r1);
Satya
  • 8,693
  • 5
  • 34
  • 55