preg_split regex on different characters

176 views Asked by At

I am trying to split up some titles into 3 parts:

Title: Name -- Edition

I'd like to split up these strings into

Array
(
    [0] => Title
    [1] => Name
    [2] => Edition
)

These titles may not have the edition, or the name field, or either of them.

Any help with this regex would be greatly appreciated.

EDIT

Thanks for everyones answers - I actually wrote this answer really quick as I had to step out the next minute. The "Title" "Name" and "Edition" can have other characters possibly I'm not entirely sure but it is possible. For example: This is the Title?: The Specific Name 012 -- An individual Edition!!

These characters (if they appear) will always be unique (: and --)

I will look over everyones answers in the morning, thank you for all your answers.

EDIT #2

To Clarify a little better, The title may or may not contain a name & edition, therefore these are also possible:

This is the title! -- An Edition?? which should return:

Array
(
    [0] => This is the title!
    [1] => 
    [2] => An Edition??
)

Or

This is the title!: A Name.. which should return

Array
(
    [0] => This is the title!
    [1] => A Name..
    [2] => 
)

Or just

This is the title! which should return

Array
(
    [0] => This is the title!
    [1] => 
    [2] => 
)

Maybe regex is not the best solution for this? I don't know enough about regex unfortunately :(

3

There are 3 answers

5
bagonyi On BEST ANSWER

This should work when Title, Name or Edition is not just one word:

preg_match("/([^:-]+(?=(?::|--|$))) (?::\s)? ([^(--)]*(?=(?:--|$))) (?:--\s)? (.*)/x", 'Long Title: With Long Name -- And an Edition', $output);

$output:

Array
(
    [0] => Long Title: With Long Name -- And an Edition
    [1] => Long Title
    [2] => With Long Name
    [3] => And an Edition
)

Regular expression visualization

Debuggex Demo

1
Darragh Enright On

You can use preg_match_all()

$str = 'Title: Name -- Edition';
preg_match_all('/\w+/', $str, $matches);
var_dump($matches[0])

Yields:

array(3) {
  [0] =>
  string(5) "Title"
  [1] =>
  string(4) "Name"
  [2] =>
  string(7) "Edition"
}

Hope this helps :)

0
Saif Ur Rehman On
$subject = "Title: Name -- Edition";
preg_match("/(.+): (.+) -- (.+)/i", $subject, $matches);

Therefore

$matches[0] == "Title"
$matches[1] == "Name"
$matches[2] == "Edition"

Not tested