Jump to content

[SOLVED] white space manipulation


b00ker_b0y

Recommended Posts

hey people.

 

got a string i.e. "Hello World 2007".

 

aim is to remove only one white space when prompted ie. remove the first and end up with "HelloWorld 2007" or the 2nd and achieve "Hello World2007". Could be a string with more white space.

 

Any functions that single out a specified character? but only 1 such as take the 2nd white space but leave the first?

 

thanks

Link to comment
Share on other sites

Here are two different solutions:

 

You can use regex to replace the nth appearance of space like

 

<?php
$n = 1;
$string = preg_replace("/([^ ]*( [^ ]*){{$n}}) /", '$1','Hello World 2007', 1);
?>

 

Or use strpos to find the nth appearance of space like:

 

<?php
$string = 'Hello World 2007';
$n = 1;
$pos = 0;
for ($i = 0; $i < $n; $i++)
{
$pos = strpos($string, ' ', $pos) + 1;
}
$string = substr_replace($string, '', strpos($string, ' ', $pos), 1);
?>

 

In both cases the $n is the nth occurance - 1 you want to remove (e.g. $n = 1 would remove the second space). If you make a function out of it, it's probably a good idea to make sure using substr_count that the string has required amount of spaces for removing.

Link to comment
Share on other sites

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • 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.