Remove extra spaces from string in php

There are times when we have strings with adjacent spaces in between. And we want to remove these unwanted spaces and the trim() function doesn't work as it trims only from start and end.

This can be done with a simple preg_replace() function call. Look at the code..


  $s = preg_replace("/\s+/"," ",html_entity_decode($string));


Example call

$string = "This    is    the      text     !!";
$string = preg_replace("/\s+/"," ",html_entity_decode($string));
echo $string;

This code will remove all adjacent spaces from the string including   spaces as well.
Remove extra spaces from string in php Remove extra spaces from string in php Reviewed by Altaf Hussain on 9:03 PM Rating: 5

No comments:

Altaf Web. Powered by Blogger.