b00ker_b0y Posted October 2, 2007 Share Posted October 2, 2007 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 More sharing options...
Rithiur Posted October 2, 2007 Share Posted October 2, 2007 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 https://forums.phpfreaks.com/topic/71523-solved-white-space-manipulation/#findComment-360093 Share on other sites More sharing options...
b00ker_b0y Posted October 3, 2007 Author Share Posted October 3, 2007 Thanks buddy Link to comment https://forums.phpfreaks.com/topic/71523-solved-white-space-manipulation/#findComment-360660 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.