The function Preg_Spilit is used to take a string, and put it into an array. The string is broken up into different values in the array based upon your input. It is phrased aspreg_split ( split_pattern, your_data, optional_limit, optional_flags )
<?php
$str = 'I like goats. You like cats. He likes dogs.';
$chars =preg_split('//', $str);
print_r($chars); echo "<p>";
$words=preg_split('/ /', $str);
print_r($words);
echo "<p>";
$sentances=preg_split('/\./', $str, -1 , PREG_SPLIT_NO_EMPTY); print_r($sentances);
?>
In the code above we preform three splits. In our first, we split the data by each character. In the second, we split it with a blank space, thus giving each word (and not each letter) an array entry. And in our third example we use a '.' period to split the data, therefor giving each sentence it's own array entry.
Because in our last example we use a '.' period to split, a new entry is started after our final period, so we add the flag PREG_SPLIT_NO_EMPTY so that no empty results are returned. Other available flags are PREG_SPLIT_DELIM_CAPTURE which also captures the character you are splitting by (our "." for example) andPREG_SPLIT_OFFSET_CAPTURE which captures the offset in characters where the split has occurred.
Remember that the split_pattern needs to be a regular expression, and that a limit of -1 (or no limit) is the default if none is specified.
0 comments:
Post a Comment