how to split by letter-followed-by-period?
I want to split text by the letter-followed-by-period rule. So I do this:
$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/\w\./", $text);
print_r($splitted_text);
Then I get this:
Array ( [0] => One tw [1] => Three tes [2开发者_JS百科] => And yet another one )
But I do need it to be like this:
Array ( [0] => One two [1] => Three test [2] => And yet another one )
How to settle the matter?
Its splitting on the letter and the period. If you want to test to make sure that there is a letter preceding the period, you need to use a positive look behind assertion.
$text = 'One two. Three test. And yet another one';
$splitted_text = preg_split("/(?<=\w)\./", $text);
print_r($splitted_text);
use explode
statement
$text = 'One two. Three test. And yet another one';
$splitted_text = explode(".", $text);
print_r($splitted_text);
Update
$splitted_text = explode(". ", $text);
using ". " the explode
statement check also the space.
You can use any kind of delimiters also a phrase non only a single char
Using regex is an overkill here, you can use explode
easily. Since a explode based answer is already give, I'll give a regex based answer:
$splitted_text = preg_split("/\.\s*/", $text);
Regex used: \.\s*
\.
- A dot is a meta char. To match a literal match we escape it.\s*
- zero or more white space.
If you use the regex: \.
You'll have some leading spaces in some of the pieces created.
精彩评论