Home > Software design >  How to explode a string that has very specific set of characters in php?
How to explode a string that has very specific set of characters in php?

Time:07-03

If I have a text output like this:

a. Hello my name is xxx.
b. Hello is my name yyy?
c. Hello my name is rrr!
d. Hello my name is aaa

All the sentences may finish with different kind of characters, so really the important issue to solve is the separation of the string based on the [letter]. string. The text comes as 1 single string:

$string = "a. Hello my name is xxx.b. Hello is my name yyy?c. Hello my name is rrr!d. Hello my name is aaa";

I would like to take the string and explode each sentence based on:

a.
b.
c.
d.

Then put each sentence into an array.

This is where I am at for now, the delimiters are: a. b. c. d.

<?php
$input = "a. Hello world aaa.
b. Hello world bbb,
c. Hello world ccc?
d. Hello world ddd!
e. Hello world eee;
f. Hello world fff?"

$regex = '^1\..*2\..*3\..*4\..*5\..*6\..*$';

echo preg_match($regex, $input);

CodePudding user response:

I've made one with preg_split().

$str = "a. Hello my name is xxx.
b. Hello is my name yyy?
c. Hello my name is rrr!
d. Hello my name is aaa";
$res = preg_split("/\n[a-z].\s/", "\n" . $str);
array_shift($res);
print_r($res);

This will output:

Array
(
    [0] => Hello my name is xxx.
    [1] => Hello is my name yyy?
    [2] => Hello my name is rrr!
    [3] => Hello my name is aaa
)

See: PHP fiddle

The regular expression looks for four characters:

  1. \n a line-feed
  2. [a-z] character between a-z
  3. . a point
  4. \s any whitespace
  •  Tags:  
  • php
  • Related