2

I read other related posts, but impossible to make it works in my case.

I have the following text :

This. Is a test. I show. You.

I want to use preg_split using delimiter '. ' (dot + space), but i need to keep delimiter in returned array. Here is the needed result :

array(
    '0' => 'This.',
    '1' => 'Is a test.',
    '2' => 'I show.',
    '3' => 'You.',
);  

What i've already tried :

preg_split("/(\.\s/)", $text, -1, PREG_SPLIT_DELIM_CAPTURE | PREG_SPLIT_NO_EMPTY);
user2733521
  • 439
  • 5
  • 22

4 Answers4

6

Use a zero-width assertion (a lookbehind here):

$result = preg_split('~(?<=\.)\s~', $text, -1, PREG_SPLIT_NO_EMPTY);

or you can use the \K feature that removes all on the left from the whole match:

$result = preg_split('~\.\K\s~', $text, -1, PREG_SPLIT_NO_EMPTY);

Without regex (if whitespaces are only spaces, and if the last dot is not followed by a space):

$chunks = explode('. ', $text);
$last = array_pop($chunks);
$result = array_map(function ($i) { return $i . '.'; }, $chunks);
$result[] = $last;

or better:

$result = explode(' #&§', strtr($text, ['. '=>'. #&§']));
Casimir et Hippolyte
  • 88,009
  • 5
  • 94
  • 125
  • @nevermind: See the wanted result carefully, you will see that spaces are not here. – Casimir et Hippolyte Aug 24 '15 at 14:45
  • Yes, you are right, but this confused me: but i need to keep delimiter in returned array? If spaces aren't needed, great. :) +1, in any case... – sinisake Aug 24 '15 at 14:45
  • I need the `\K`, but to the right :) I can't find the propper letter, which is it? – Tomas Votruba Jul 27 '18 at 10:39
  • 1
    @TomášVotruba: there's no escape sequence with a letter for the right. The way to do it is to enclose the right part into a lookahead assertion: `part_I_need(?=right_part)` or to use a capture group: `(part_I_need)right_part`. Note that when you use a lookahead, the right part characters aren't consumed and can be reused for the next match. – Casimir et Hippolyte Jul 27 '18 at 18:58
2

try this

$matches = preg_split("/ (?=.)/", $text);
var_dump( $matches);
Syed mohamed aladeen
  • 6,507
  • 4
  • 32
  • 59
0

It is not solution with regex, but another variant. Probably it will work for you too:

$text = "This. Is a test. I show. You.";

$result = explode('DELIM', str_replace('. ', '.DELIM', $text));
Vladimir Gilevich
  • 861
  • 1
  • 10
  • 17
0

Using preg_split() and something more

$text="This. Is a test. I show. You.";
$myVec=preg_split("/(\.\040)/", $text,-1,PREG_SPLIT_DELIM_CAPTURE);
$j=0;
for ($i = 0; $i < count($myVec); $i++) {
    if ($myVec[$i]!=". ") {
        $myNewVec[$j]=$myVec[$i];
    }else{
        $myNewVec[$j-1]=$myNewVec[$j-1].$myVec[$i];
    }
$j++;
}
echo"<pre>";
var_dump($myNewVec);
echo "</pre>";
Rodney Salcedo
  • 1,228
  • 19
  • 23