разбить строку писем на группы, если длина строки превышает 50 писем - PullRequest
0 голосов
/ 26 августа 2011

Существует ли эффективный способ разбить строку, содержащую список адресов электронной почты, на группы, скажем, 50. Скажем, у меня есть строка, которая содержит письма в формате с разделением запятыми.Что-то вроде ... email1 @ host.com, email2 @ host.com, email3 @ host.com и так далее.

Наиболее очевидный способ сделать это, вероятно, будет массив, но есть ли способ сделать это с помощью строковых функций?Я посмотрел на substr и str_split, и они, похоже, не перестают работать.

Спасибо

Ответы [ 3 ]

3 голосов
/ 26 августа 2011

Должно быть гораздо эффективнее искать 50-е вхождение запятой и разбивать строку после этого. Так что найдите эту позицию. Я думаю, что http://www.php.net/manual/en/function.strpos.php#102336 должно быть решением для этого. Затем разделите строку с помощью substr и удалите запятую в позиции 1 новой строки.

Укороченный PHP-код под ваши нужды:

<?php 

function strnpos( $haystack, $needle, $nth, $offset = 0 ) { 
    //  If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. 
    if(!is_string($needle)) 
        $needle = chr((int)$needle ); 

    //  Are the supplied values valid / reasonable? 
    $len = strlen( $needle ); 
    if(1 > $nth || 0 === $len) 
        return false; 

    //  $offset is incremented in the call to strpos, so make sure that the first 
    //  call starts at the right position by initially decreasing $offset by $len. 
    $offset -= $len; 
    do { 
        $offset = strpos( $haystack, $needle, $offset + $len ); 
    } while( --$nth  && false !== $offset ); 

    return $offset;
} 

$emails_str = 'email1@host.com,email2@host.com,email3@host.com,...';

$pos = strnpos($emails_str, ',', 50, 0);
while($pos) {
    // Do sth. with the group...
    echo substr($emails_str, 0, $pos), PHP_EOL; 

    // Cut this part out of the string
    $emails_str = substr($emails_str, $pos+1);
    $pos = strnpos($emails_str, ',', 50, 0);
}
2 голосов
/ 26 августа 2011

Да, найдите

$string="word_1, word_2, word_3"; 
$array=preg_split("/([,]{49}[,])+",$string);

Или вы можете использовать

Полный набор функций strn * pos, которые ищут n-е вхождение иглы в стоге сена.Я предпочитаю эту реализацию strnpos, потому что она не дает видимых предупреждений, когда поставляется с иглой длиной 0 (что, по общему признанию, нестандартное поведение).Основано на версии I [первоначально опубликовано 05-MAR-2010];эта новая версия больше соответствует семантике strpos.

<?php 

/** 
 *  This function implements all the strn*pos functions, which return the $nth occurrence of $needle 
 *  in $haystack, or false if it doesn't exist / when illegal parameters have been supplied. 
 * 
 *  @param  string  $haystack       the string to search in. 
 *  @param  MIXED   $needle         the string or the ASCII value of the character to search for. 
 *  @param  integer $nth            the number of the occurrence to look for. 
 *  @param  integer $offset         the position in $haystack to start looking for $needle. 
 *  @param  bool    $insensitive    should the function be case insensitive? 
 *  @param  bool    $reverse        should the function work its way backwards in the haystack? 
 *  @return MIXED   integer         either the position of the $nth occurrence of $needle in $haystack, 
 *               or boolean         false if it can't be found. 
 */ 
function strnripos_generic( $haystack, $needle, $nth, $offset, $insensitive, $reverse ) 
{ 
    //  If needle is not a string, it is converted to an integer and applied as the ordinal value of a character. 
    if( ! is_string( $needle ) ) { 
        $needle = chr( (int) $needle ); 
    } 

    //  Are the supplied values valid / reasonable? 
    $len = strlen( $needle ); 
    if( 1 > $nth || 0 === $len ) { 
        return false; 
    } 

    if( $insensitive ) { 
        $haystack = strtolower( $haystack ); 
        $needle   = strtolower( $needle   ); 
    } 

    if( $reverse ) { 
        $haystack = strrev( $haystack ); 
        $needle   = strrev( $needle   ); 
    } 

    //  $offset is incremented in the call to strpos, so make sure that the first 
    //  call starts at the right position by initially decreasing $offset by $len. 
    $offset -= $len; 
    do 
    { 
        $offset = strpos( $haystack, $needle, $offset + $len ); 
    } while( --$nth  && false !== $offset ); 

    return false === $offset || ! $reverse ? $offset : strlen( $haystack ) - $offset; 
} 

/** 
 *  @see    strnripos_generic 
 */ 
function strnpos( $haystack, $needle, $nth, $offset = 0 ) 
{ 
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, false ); 
} 

/** 
 *  @see    strnripos_generic 
 */ 
function strnipos( $haystack, $needle, $nth, $offset = 0 ) 
{ 
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, false ); 
} 

/** 
 *  @see    strnripos_generic 
 */ 
function strnrpos( $haystack, $needle, $nth, $offset = 0 ) 
{ 
    return strnripos_generic( $haystack, $needle, $nth, $offset, false, true ); 
} 

/** 
 *  @see    strnripos_generic 
 */ 
function strnripos( $haystack, $needle, $nth, $offset = 0 ) 
{ 
    return strnripos_generic( $haystack, $needle, $nth, $offset, true, true ); 
} 

$haystack = 'Dit is een HoTtentotTentenTentenToonstellingTest!'; 

echo strnpos  ( $haystack, 't', 5 ), ' === ', strnpos  ( $haystack, 116, 5 ), PHP_EOL; 
echo strnipos ( $haystack, 't', 5 ), ' === ', strnipos ( $haystack, 116, 5 ), PHP_EOL; 
echo strnrpos ( $haystack, 't', 5 ), ' === ', strnrpos ( $haystack, 116, 5 ), PHP_EOL; 
echo strnripos( $haystack, 't', 5 ), ' === ', strnripos( $haystack, 116, 5 ), PHP_EOL; 
echo PHP_EOL; 
echo strnpos  ( $haystack, 'T', 5 ), ' === ', strnpos  ( $haystack,  84, 5 ), PHP_EOL; 
echo strnipos ( $haystack, 'T', 5 ), ' === ', strnipos ( $haystack,  84, 5 ), PHP_EOL; 
echo strnrpos ( $haystack, 'T', 5 ), ' === ', strnrpos ( $haystack,  84, 5 ), PHP_EOL; 
echo strnripos( $haystack, 'T', 5 ), ' === ', strnripos( $haystack,  84, 5 ), PHP_EOL; 
?>
1 голос
/ 26 августа 2011
$emails = 'email1@host.com,email2@host.com,email3@host.com,...';
if( substr_count( $emails, '@' ) > 50 )
{
    $groups = explode( ',', $emails );
    $groups = array_chunk( $groups, 50 );

    $emails = '';
    foreach( $groups as $k => $group )
    {
        $group_data = implode( ', ', $group );
        $emails .= "{$group_data}<hr/>";
    }
}
echo $emails;
...