note 25099 deleted from function.preg-split by sniper
| From: | sniper@php.net | Date: | Tue, 30 Sep 2003 12:34:28 +0000 |
| Subject: | note 25099 deleted from function.preg-split by sniper | ||
| References: | 1 | Groups: | php.notes |
| Request: | Send a blank email to php-notes+get-57489@lists.php.net to get a copy of this message | ||
Note Submitter: slevy1 at pipeline dot com
----
To split a string at the beginning of each line, use a positive lookahead with preg_split. Note,
preg_split must have the proper LIMIT parameter for this to work correctly, as follows:
<?php
function SplitNow($split_pat,$s,$n) {
$vals = preg_split($split_pat,$s,$n);
$i=0;
foreach ($vals as $v) {
echo "$i. $v <br>\n";
$i++;
}
echo '<p><pre>';
print_r($vals);
echo '</pre></p>';
}
$str = "Are roses red?\nAre violets blue?\nAre flowers green or ever purple?\nAre we having fun
yet?\n";
echo "Test string is:<P>\n$str<BR><HR color=navy size=6><P>";
$splitter='/(?=^Are)/m'; // split at pt where line begins with 'Are'
$vals = preg_split($splitter,$str); // split into array
$num = count($vals); // and get number of elements
echo "<BR>LIMIT is $num<P>\n"; // LIMIT should be number of array
elements
SplitNow($splitter,$str,$num);
?>