Skip to content
Advertisement

How to split text based on specific word

I have a text which contains the word “Article” many times for example:

My text title Article 1 bla bla Article 2 bla bla …

I want to split the text like this:

Text1=Article 1 bla bla
Text2=Article 2 bla bla
...

Advertisement

Answer

Instead of trying to find a split pattern, you should look for a matching pattern:

/Article.*?(?=Article|$)/

It matches Article, followed by anything up to but not including another Article or end of line.

$str = 'some ething Article 1 2 3 Article 5 6 7';

preg_match_all('/Article.*?(?=Article)/', $str, $matches);
print_r($matches[0]);

Output:

Array
(
    [0] => Article 1 2 3 
    [1] => Article 5 6 7
)

Edit

To just filter out the Article followed by a number:

preg_match_all('/Article d+/', $str, $matches);
// $matches[0] contains "Article 1" and "Article 5"
User contributions licensed under: CC BY-SA
5 People found this is helpful
Advertisement