You are here: Re: Change alternate commas to semi colons... « PHP Programming Language « IT news, forums, messages
Re: Change alternate commas to semi colons...

Posted by Ken Robinson on 06/20/06 20:14

Juliette wrote:

> I don't think you can easily do it with regex as you can't really
> differentiate between comma's.
> I would suggest something along the lines of:
>
> $array = explode ( ', ', $string );
> $arraycount = count($array);
> $new_string = '';
>
> for( $i=0; $i<$arraycount; $i++; ) {
> if ((1&$i)) {
> //$i is odd
> $new_string .= $array[$i] . ', ';
> }
> elseif (!(1&$num)) {
> //$i is even
> $new_string .= $array[$i] . '; ';
> }
> }
> $string = $new_string;
> unset($new_string);

I would use temporary arrays and the implode() function, and a switch
statement instead of the if/elseif:

<?php
$string = "Carson, David, Milne, Rebecca, Pakes, Francis J., Shalev,
Karen, Shawyer, Andrea";
$array = explode ( ', ', $string );
$tmp = array();
$tmp2 = array();
for( $i=0; $i<count($array); $i++ ) {
switch ($i % 2) {
case 0:
$tmp2[] = trim($array[$i]);
break;
case 1:
$tmp2[] = trim($array[$i]);
$tmp[] = implode(', ',$tmp2);
$tmp2 = array();
break;
}
}
echo 'Before: ' . $string . "\n";
$string = implode('; ',$tmp);
echo 'After: ' . $string;
?>

Ken

 

Navigation:

[Reply to this message]


Удаленная работа для программистов  •  Как заработать на Google AdSense  •  England, UK  •  статьи на английском  •  PHP MySQL CMS Apache Oscommerce  •  Online Business Knowledge Base  •  DVD MP3 AVI MP4 players codecs conversion help
Home  •  Search  •  Site Map  •  Set as Homepage  •  Add to Favourites

Copyright © 2005-2006 Powered by Custom PHP Programming

Сайт изготовлен в Студии Валентина Петручека
изготовление и поддержка веб-сайтов, разработка программного обеспечения, поисковая оптимизация