Tutorial :php tagging, remove multiple spaces


I have the following code

//check out the tags, if it allready exist update with 1 if not create new record          $tag_item = "";          $tags = explode(" ", $tags);          foreach($tags as $tag):              if(!empty($tag) && $tag != " "):                  $t_sql = mysqli_query($link, "SELECT id, times FROM shop_tags WHERE tag='".$tag."'");                  if(mysqli_num_rows($t_sql) == 0):                      mysqli_query($link, "INSERT INTO shop_tags (tag, times) VALUES ('".$tag."', 1)");                      //find last updated id of the tags                      $lastid = mysqli_insert_id($link);                      $tag_item .= $lastid." ";                  endif;              endif;          endforeach;  

So I use explode to seperate each tag, but what if a user by accident added to spaces? should I use preg_match first to filter for this? and how do I remove the last white space if there is any?


To remove white spaces, the first though is to use trim(), which you could either do in the loop for each tag

foreach($tags as $tag):      $tag = trim($tag);  

or before:

$tags = explode(" ", $tags);  $tags = array_map('trim', $tags);  

In both cases, you will end up having to filter out the empty items in $tags

foreach($tags as $tag):      $tag = trim($tag); //This line is only required if you didn't use array_map      if ( empty($tag){          continue;      }  

So it would possibly just be better to use preg_replace

$tags = preg_replace('/\s\s+/',' ', $tags);  $tags = explode(' ', $tags);  

Which would ensure that multiple white spaces are converted into a single space before exploding.


First remove possible one or more empty spaces:

$tags = preg_replace('/\s\s+/',' ', $tags);  

Remove ending space if there is one:

$tags = ltrim($tags);  

And then you explode and proceed further:

$tags = explode(' ', $tags);  


$tags = explode(" ", $tags);  

This'll explode spaces into their own tags. Filter yourself with the foreach, which you do. Modify that if...


You could also trim ahead of time.

array_filter($tags, "trim");  

Personally, I use commas to delimit tags to allow for tags that have spaces.


You could search for (\s)+ and replace it with a single space. Then trim your string to take care of any trailing white-space.


You could use the preg functions - but the str_replace function is a lot faster in this case. Also, regarless of which approach you take, you need to apply the method TWICE - in case there are an odd number of consecutive spaces (greater than 1):

$tags=str_replace('  ',' ',trim($tags)); // replace 2 spaces with 1  $tags=str_replace('  ',' ',$tags); // again  $tags=explode(' ', $tags);  


Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Next Post »