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
https://forums.phpfreaks.com/topic/71523-solved-white-space-manipulation/
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.

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.