Разделить строку пополам php

chunk_split

Функция используется для разбиения строки на фрагменты, например, для приведения результата функции base64_encode() в соответствие с требованиями RFC 2045. Она вставляет строку separator после каждых length символов.

Список параметров

Последовательность символов, используемая в качестве конца строки.

Возвращаемые значения

Возвращает преобразованную строку.

Примеры

Пример #1 Пример использования chunk_split()

// форматирование данных в соответствии с RFC 2045
$new_string = chunk_split ( base64_encode ( $data ));
?>

Смотрите также

  • str_split() — Преобразует строку в массив
  • explode() — Разбивает строку с помощью разделителя
  • wordwrap() — Переносит строку по указанному количеству символов
  • » RFC 2045

User Contributed Notes 20 notes

An alternative for unicode strings;

function chunk_split_unicode ( $str , $l = 76 , $e = «\r\n» ) $tmp = array_chunk (
preg_split ( «//u» , $str , — 1 , PREG_SPLIT_NO_EMPTY ), $l );
$str = «» ;
foreach ( $tmp as $t ) $str .= join ( «» , $t ) . $e ;
>
return $str ;
>

$str = «Yarım kilo çay, yarım kilo şeker» ;
echo chunk_split ( $str , 4 ) . «\n» ;
echo chunk_split_unicode ( $str , 4 );
?>

Yar�
�m k
ilo
çay
, ya
rım
kil
o ş
eker

As an alternative for qeremy [atta] gmail [dotta] com
There is much shorter way for binarysafe chunking of multibyte string:

function word_chunk ( $str , $len = 76 , $end = «\n» ) $pattern = ‘~.~u’ ; // like «~.~u»
$str = preg_replace ( $pattern , ‘$0’ . $end , $str );
return rtrim ( $str , $end );
>

$str = ‘русский’ ;
echo chunk_split ( $str , 3 ) . «\n» ;
echo word_chunk ( $str , 3 ) . «\n» ;
?>

р�
�с
с�
�и
й

I’m not sure what versions this also occurs in but the output of chunk_split() in PHP 5.0.4 does not match the output in other versions of PHP.

In all versions of PHP I have used, apart from 5.0.4 chunk_split() adds the separator (\r\n) to the end of the string. But in PHP 5.0.4 this does not happen. This had a fairly serious impact on a library I maintain so it may also affect others who are not aware of this.

the best way to solve the problem with the last string added by chunk_split() is:

$string = ‘1234’ ;
substr ( chunk_split ( $string , 2 , ‘:’ ), 0 , — 1 );
// will return 12:34
?>

Not quite completely obvious, but.

you can un_chunk_split() by:

$long_str = str_replace( «\r\n», «», $chunked_str );

This function is very simple and many other functions make this on PHP 5 and even some ones in 4 the good think about this one is that work on php 3.0.6 and 4

function split_hjms_chars($xstr, $xlenint, $xlaststr)
$texttoshow = chunk_split($xstr,$xlenint,»\r\n»);
$texttoshow = split(«\r\n»,$texttoshow);
$texttoshow = $texttoshow[0].$xlaststr;
return $texttoshow;
>

echo split_hjms_chars(«This is your text»,6,». «);

It is useful to cut long text on preview lists and if the server it’s old.

Hope it helps some one. Hans Svane

«version» of chunk_split for cyrillic characters in UTF-8

public function UTFChunk($Text,$Len = 10,$End = «\r\n»)
if(mb_detect_encoding($Text) == «UTF-8»)
return mb_convert_encoding(
chunk_split(
mb_convert_encoding($Text, «KOI8-R»,»UTF-8″), $Len,$End
),
«UTF-8», «KOI8-R»
);
> else
return chunk_split($Text,$Len,$End);
>
>

this is example for russian language

Here’s a version of Chunk Split I wrote that will not split html entities. Useful if you need to inject something in html (in my case, tags to allow for long text wrapping).

If you are using UTF-8 charset you will face a problem with Arabic language
to solve this problem i used this function

function chunk_split_ ( $text , $length , $string_end )
<
$text = iconv ( «UTF-8» , «windows-1256» , $text );
$text = str_split ( $text );
foreach( $text as $val )
<
if( $a !== $val )
<
$a = $val ;
$x = 0 ;
>else <
$a = $val ;
$x ++;
>
if( $x > $length )
<
$new_text .= $val . $string_end ;
$x = 0 ;
>else
<
$new_text .= $val ;
>

>
$new_text = iconv ( «windows-1256» , «UTF-8» , $new_text );
return $new_text ;
>
?>

Important note is the maximum line length and the recommended one. The standard says:
«Lines in a message MUST be a maximum of 998 characters excluding the CRLF, but it is RECOMMENDED that lines be limited to 78 characters excluding the CRLF. «

See PHP manual for chunk_split() Which is set to 76 characters long chunk and «\r\n» at the end of line by default.

I’ve found this quite useful for simulating various kinds of shuffles with cards. It is humorous but can imitate multiple deck cuts and other (imperfectly) random events.

function truffle_shuffle ( $body , $chunklen = 76 , $end = «\r\n» )
<
$chunk = chunk_split ( $body , $chunklen , «-=blender=-» );
$truffle = explode ( «-=blender=-» , $chunk );
$shuffle = shuffle ( $truffle );
$huknc = implode ( $end , $shuffle );
return $huknc ;
>
?>

When using ssmtp for simple command line mailing:

$mail_to = «destination@emailbox.com»;
$msg = «this would be an actual base64_encoded gzip msg»;
$date = date(r);
$mail = «X-FROM: root@sender.org \n»;
$mail .= «X-TO: «.$mail_to. » \n»;
$mail .= «To: «.$mail_to. » \n»;
$mail .= «Date: $date \n»;
$mail .= «From: root@sender.org \n»;
$mail .= «Subject: lifecheck \n»;
$mail .= $msg.» \n»;
exec(«echo ‘$mail’ | /usr/sbin/ssmtp «.$mail_to);

be sure to invoke chunk_split() on your message body — ssmtp becomes unhappy with long lines and will subsequently trash your message.

>> chunk_split will also add the break _after_ the last occurence.

this should be not the problem

substr(chunk_split(‘FF99FF’, 2, ‘:’),0,8);
will return FF:99:FF

In reply to «adrian at zhp dot inet dot pl» digit grouping function:
$number = strrev ( chunk_split ( strrev ( $number ), 3 , ‘ ‘ ));
//If $number is ‘1234567’, result is ‘1 234 567’.
?>

There is a much more simple way of doing this, by using the built-in number_format() function.

$number = number_format ( $number , 2 , «.» , » » );

//This will round $number to 2 decimals, use the dot («.»)
//as decimal point, and the space (» «) as thousand sepparator.

Источник

str_split

If the optional length parameter is specified, the returned array will be broken down into chunks with each being length in length, except the final chunk which may be shorter if the string does not divide evenly. The default length is 1 , meaning every chunk will be one byte in size.

Errors/Exceptions

If length is less than 1 , a ValueError will be thrown.

Changelog

Version Description
8.2.0 If string is empty an empty array is now returned. Previously an array containing a single empty string was returned.
8.0.0 If length is less than 1 , a ValueError will be thrown now; previously, an error of level E_WARNING has been raised instead, and the function returned false .

Examples

Example #1 Example uses of str_split()

$arr1 = str_split ( $str );
$arr2 = str_split ( $str , 3 );

print_r ( $arr1 );
print_r ( $arr2 );

The above example will output:

Array ( [0] => H [1] => e [2] => l [3] => l [4] => o [5] => [6] => F [7] => r [8] => i [9] => e [10] => n [11] => d ) Array ( [0] => Hel [1] => lo [2] => Fri [3] => end )

Notes

Note:

str_split() will split into bytes, rather than characters when dealing with a multi-byte encoded string. Use mb_str_split() to split the string into code points.

See Also

  • mb_str_split() — Given a multibyte string, return an array of its characters
  • chunk_split() — Split a string into smaller chunks
  • preg_split() — Split string by a regular expression
  • explode() — Split a string by a string
  • count_chars() — Return information about characters used in a string
  • str_word_count() — Return information about words used in a string
  • for

User Contributed Notes 3 notes

The function str_split() is not ‘aware’ of words. Here is an adaptation of str_split() that is ‘word-aware’.

$array = str_split_word_aware (
‘In the beginning God created the heaven and the earth. And the earth was without form, and void; and darkness was upon the face of the deep.’ ,
32
);

/**
* This function is similar to str_split() but this function keeps words intact; it never splits through a word.
*
* @return array
*/
function str_split_word_aware ( string $string , int $maxLengthOfLine ): array
if ( $maxLengthOfLine <= 0 ) throw new RuntimeException ( sprintf ( 'The function %s() must have a max length of line at least greater than one' , __FUNCTION__ ));
>

$lines = [];
$words = explode ( ‘ ‘ , $string );

$currentLine = » ;
$lineAccumulator = » ;
foreach ( $words as $currentWord )

$currentWordWithSpace = sprintf ( ‘%s ‘ , $currentWord );
$lineAccumulator .= $currentWordWithSpace ;
if ( strlen ( $lineAccumulator ) < $maxLengthOfLine ) $currentLine = $lineAccumulator ;
continue;
>

// Overwrite the current line and accumulator with the current word
$currentLine = $currentWordWithSpace ;
$lineAccumulator = $currentWordWithSpace ;
>

if ( $currentLine !== » ) $lines [] = $currentLine ;
>

array( 5 ) [ 0 ]=> string ( 29 ) «In the beginning God created »
[ 1 ]=> string ( 30 ) «the heaven and the earth. And »
[ 2 ]=> string ( 28 ) «the earth was without form, »
[ 3 ]=> string ( 27 ) «and void; and darkness was »
[ 4 ]=> string ( 27 ) «upon the face of the deep. »
>

Источник

Split string into 2 pieces by length using PHP

I have a very long string that I want to split into 2 pieces. I ws hoping somebody could help me split the string into 2 separate strings. I need the first string to be 400 characters long and then the rest in the second string.

There still is a section in the PHP Manual called String Functions. And: Going through your previous questions I cannot but notice that there is lots of questions that are easily answered by searching the PHP Manual or Google or Stack Overflow. You are encouraged to do some research before asking new questions here. See stackoverflow.com/questions/ask-advice

It’s not actually a duplicate of that, I don’t think. This is looking to pull out a «teaser» of N characters to one string, then the rest of the original to a second string — only 2 total. The linked question is asking to split the string into as many parts as needed.

3 Answers 3

$first400 = substr($str, 0, 400); $theRest = substr($str, 400); 

You can rename your variables to whatever suits you. Those names are just for explanation. Also if you try this on a string less than 400 characters $theRest will be FALSE

There is a function called str_split PHP Manual which might, well, just split strings:

$parts = str_split($string, $split_length = 400); 

$parts is an array with each part of it being 400 (single-byte) characters at max. As per this question, you can as well assign the first and second part to individual variables (expecting the string being longer than 400 chars):

list($str_1, $str_2) = str_split(. ); 

Источник

Читайте также:  Уроки java от алишева
Оцените статью