Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to explode a string that has very specific set of characters in php?

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";

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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);

>Solution :

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading