note 118326 added to function.preg-split
| From: | canadian dot in dot exile at gmail dot com | Date: | Wed, 18 Nov 2015 00:27:15 +0000 |
| Subject: | note 118326 added to function.preg-split | ||
| Groups: | php.notes | ||
| Request: | Send a blank email to php-notes+get-204172@lists.php.net to get a copy of this message | ||
This regular expression will split a long string of words into an array of sub-strings, of some
maximum length, but only on word-boundries.
I use the reg-ex with preg_match_all(); but, I'm posting this example here (on the page for
preg_split()) because that's where I looked when I wanted to find a way to do this.
Hope it saves someone some time.
<?php
// example of a long string of words
$long_string = 'Your IP Address will be logged with the submitted note and made public on the
PHP manual user notes mailing list. The IP address is logged as part of the notes moderation
process, and won\'t be shown within the PHP manual itself.';
// "word-wrap" at, for example, 60 characters or less
$max_len = 60;
// this regular expression will split $long_string on any sub-string of
// 1-or-more non-word characters (spaces or punctuation)
if(preg_match_all("/.{1,{$max_len}}(?=\W+)/", $long_string, $lines) !== False) {
// $lines now contains an array of sub-strings, each will be approx.
// $max_len characters - depending on where the last word ended and
// the number of 'non-word' characters found after the last word
for ($i=0; $i < count($lines[0]); $i++) {
echo "[$i] {$lines[0][$i]}\n";
}
}
?>
----
Server IP: 72.52.91.14
Probable Submitter: 172.97.96.90
----
Manual Page -- http://php.net/manual/en/function.preg-split.php
Edit -- https://master.php.net/note/edit/118326
Del: integrated -- https://master.php.net/note/delete/118326/integrated
Del: useless -- https://master.php.net/note/delete/118326/useless
Del: bad code -- https://master.php.net/note/delete/118326/bad+code
Del: spam -- https://master.php.net/note/delete/118326/spam
Del: non-english -- https://master.php.net/note/delete/118326/non-english
Del: in docs -- https://master.php.net/note/delete/118326/in+docs
Del: other reasons-- https://master.php.net/note/delete/118326
Reject -- https://master.php.net/note/reject/118326
Search -- https://master.php.net/manage/user-notes.php