Search code examples
phpregexpreg-split

preg_split regex on different characters


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 :(


Solution

  • 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