Trung Tran
Trung Tran

Reputation: 299

Match substrings separated by a word with a regular expression

I have a sentence like this: "AOrbOrCOrDOreOrdOr..." . I'm trying to match all the word like "A", "b", "C" and so on. But, it just returns "A", "bOr", "cOr",... Here is my pattern: /(.*?(?:(?=Or))|(?<!Or).*?)/. I'm very new to Regular Expression.

Upvotes: 1

Views: 109

Answers (3)

you can use explode function:

$text  = "AOrbOrCOrDOreOrdOr...";
$array = explode('Or', $text);

and then you have now an array with the parts:

array("A", "b", "C", "D", "e",) // ...and so on

Upvotes: -1

hek2mgl
hek2mgl

Reputation: 157967

An alternative to using a regex would be to use explode():

$string = 'AOrbOrCOrDOreOrdOr...';
$words = explode('Or', $string);

Note that if you are having a constant delimiter, like Or, you can use explode() which is faster than using a regex.

Upvotes: 5

Avinash Raj
Avinash Raj

Reputation: 174706

Just use a lookahead in your regex to match all the alphabets which are followed by the string Or,

[A-Za-z](?=Or)

DEMO

If you want to match any character followed by the string Or, then you could use . instead of [A-Za-z].

.(?=Or)

DEMO

Upvotes: 0

Related Questions