Replace whitespaces with a comma for the first few occurance

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
l_kris06
Forum Newbie
Posts: 3
Joined: Tue Feb 05, 2008 5:58 am

Replace whitespaces with a comma for the first few occurance

Post by l_kris06 »

Hi all,

I need to replace whitespaces with a comma only for the first few occurances. For example:

$data = SIP25071 O 4.4 43 4 ERG 02/28/2008 Mike cisco2000 ptime.baseval header, incorrect chk in.

my desired output is:
--------------------
SIP25071,O,4.4,43,4,ERG,02/28/2008,Mike,cisco2000,ptime.baseval header incorrect chk in.

These data are individual bug statistics. I eventually want to write to the database, hence the need for the delimiter.

I would really appreciate, if somebody can help me out.


/Kris


This is wht i have got so far:

Code: Select all

<?php
  $str=SIP25071,O,4.4,43,4,ERG,02/28/2008,Mike,cisco2000,ptime.baseval header incorrect chk in.';
  $rpl=preg_replace('@([A-Z0-9]+)( )@','$1,',$str);
  echo "$rpl";
?>
output:
-------
SIP25071,O,4.4,43,4,ERG,02/28/2008,Mike cisco2000,ptime.baseval header incorrect chk in.

Desired output:
--------------
SIP25071,O,4.4,43,4,ERG,02/28/2008,Mike,cisco2000,ptime.baseval header incorrect chk in.

I am stuck, can somebody please help?
User avatar
hawkenterprises
Forum Commoner
Posts: 54
Joined: Thu Feb 28, 2008 9:56 pm
Location: gresham,oregon
Contact:

Re: Replace whitespaces with a comma for the first few occurance

Post by hawkenterprises »

Hello

I might try something like this. I'm using 'ptime.' as your backend terminator and I'm not using preg replace but you might find this to execute faster.

Code: Select all

 
<?php
// chop the area we need, space delimited
$chopped = substr($str,0,strpos($str,'ptime'));
// swap spaces for commas
$diced = str_replace(' ', ',',$chopped);
// splice back the new comma delimtied and space together.
$spliced = $diced . substr($str,strpos($str,'ptime'));
 
?>
 
Post Reply