[Editor's Note: You can use php's wordwrap() to do the exact same thing]
This script splits a text into portions of a defined max. size, which will never be exceeded, and doesnt cut words. (Per portion it adds as many words as possible without exceeding the char-limit)
the only exception where a portion would be bigger than the limit, is when there's a word thats longer than the max_size, but you could quite easily change the script so it regards this.
<?
$str= 'Lorem ipsum dolor sit amet, consectetur adipisicing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum.';
$max_size = 50;
$words = preg_split("/[\040]+/", $str, -1);
$r=0;
for($i=0; $i < count($words); $i++) {
if (strlen($line[$r] . $words[$i] . ' ') < $max_size) $line[$r] .= $words[$i] . ' ';
else
{
$r++;
$line[$r] .= $words[$i] . ' ';
}
}
print_r ($line);
?>
Result:
Array
(
[0] => Lorem ipsum dolor sit amet, consectetur
[1] => adipisicing elit, sed do eiusmod tempor
[2] => incididunt ut labore et dolore magna aliqua. Ut
[3] => enim ad minim veniam, quis nostrud exercitation
[4] => ullamco laboris nisi ut aliquip ex ea commodo
[5] => consequat. Duis aute irure dolor in
[6] => reprehenderit in voluptate velit esse cillum
[7] => dolore eu fugiat nulla pariatur. Excepteur sint
[8] => occaecat cupidatat non proident, sunt in culpa
[9] => qui officia deserunt mollit anim id est laborum.
)
preg_split
(PHP 4, PHP 5)
preg_split — 正規表現で文字列を分割する
説明
array preg_split ( string $pattern, string $subject [, int $limit [, int $flags]] )指定した文字列を、正規表現で分割します。
パラメータ
- pattern
検索するパターンを表す文字列。
- subject
入力文字列。
- limit
これを指定した場合、最大 limit 個の部分文字列が返されます。そして、 limit が -1 の場合は「制限が無い」ことを意味します。 これは、flags を指定する場合に有用です。
- flags
flags は、次のフラグを組み合わせたものとする (ビット和演算子|で組み合わせる)ことが可能です。
- PREG_SPLIT_NO_EMPTY
- このフラグを設定すると、空文字列でないものだけが preg_split() により返されます。
- PREG_SPLIT_DELIM_CAPTURE
- このフラグを設定すると、文字列分割用のパターン中の カッコによるサブパターンでキャプチャされた値も同時に返されます。
- PREG_SPLIT_OFFSET_CAPTURE
このフラグを設定した場合、各マッチに対応する文字列のオフセットも返されます。 これにより、返り値は配列となり、配列の要素 0 はマッチした文字列、 要素 1 は subject におけるマッチした文字列のオフセット値となることに 注意してください。
返り値
pattern にマッチした境界で分割した subject の部分文字列の配列を返します。
変更履歴
| バージョン | 説明 |
|---|---|
| 4.3.0 | PREG_SPLIT_OFFSET_CAPTURE が追加されました。 |
| 4.0.5 | PREG_SPLIT_DELIM_CAPTURE が追加されました。 |
| 4.0.0 | パラメータ flags が追加されました。 |
例
例 1685. preg_split() の例 : 検索文字列のある部分を取得
<?php
// カンマまたは " ", \r, \t, \n , \f などの空白文字で句を分割する。
$keywords = preg_split("/[\s,]+/", "hypertext language, programming");
?>
例 1686. 文字列を文字要素に分割
<?php
$str = 'string';
$chars = preg_split('//', $str, -1, PREG_SPLIT_NO_EMPTY);
print_r($chars);
?>
例 1687. 文字列をマッチするものとそのオフセットに分割
<?php
$str = 'hypertext language programming';
$chars = preg_split('/ /', $str, -1, PREG_SPLIT_OFFSET_CAPTURE);
print_r($chars);
?>
上の例の出力は以下となります。
Array
(
[0] => Array
(
[0] => hypertext
[1] => 0
)
[1] => Array
(
[0] => language
[1] => 10
)
[2] => Array
(
[0] => programming
[1] => 19
)
)
注意
正規表現の威力を必要としないのなら、より高速な (機能はシンプルですが) 代替関数として explode() あるいは str_split() のような選択肢があります。
参考
| spliti() |
| split() |
| implode() |
| preg_match() |
| preg_match_all() |
| preg_replace() |
preg_split
14-Nov-2006 10:56
04-Dec-2005 10:53
Be advised
$arr = preg_split("/x/", "x" );
print_r($arr);
will output:
Array
(
[0] =>
[1] =>
)
That is it will catch the 2 empty string on each side of the delimiter.
24-Mar-2005 01:41
preg_split() behaves differently from perl's split() if the string ends with a delimiter. This perl snippet will print 5:
my @a = split(/ /, "a b c d e ");
print scalar @a;
The corresponding php code prints 6:
print count(preg_split("/ /", "a b c d e "));
This is not necessarily a bug (nowhere does the documentation say that preg_split() behaves the same as perl's split()) but it might surprise perl programmers.
26-Sep-2004 12:01
To clarify the "limit" parameter and the PREG_SPLIT_DELIM_CAPTURE option,
$preg_split('(/ /)', '1 2 3 4 5 6 7 8', 4 ,PREG_SPLIT_DELIM_CAPTURE );
returns
('1', ' ', '2', ' ' , '3', ' ', '4 5 6 7 8')
So you actually get 7 array items not 4
30-May-2002 04:01
The above description for PREG_SPLIT_OFFSET_CAPTURE may be a bit confusing.
When the flag is or'd into the 'flags' parameter of preg_split, each match is returned in the form of a two-element array. For each of the two-element arrays, the first element is the matched string, while the second is the match's zero-based offset in the input string.
For example, if you called preg_split like this:
preg_split('/foo/', 'matchfoomatch', -1, PREG_SPLIT_OFFSET_CAPTURE);
it would return an array of the form:
Array(
[0] => Array([0] => "match", [1] => 0),
[1] => Array([1] => "match", [1] => 8)
)
Note that or'ing in PREG_DELIM_CAPTURE along with PREG_SPLIT_OFFSET_CAPTURE works as well.