Johan
Johan

Reputation: 25

I'm trying to split a sentence with Regex

I've been trying to figure this out all day but how can I reliable split the next line in following order.

Passive: Marks enemies who are isolated from nearby allies. Active: Deals 70/100/130/160/190 (+) physical damage. If the target is isolated, the amount is increased to 100/145/190/235/280 (+). Evolved Enlarged Claws: Increases damage to isolated enemies by 12/12/12/12/12% of their missing health (max 200/200/200/200/200 vs. monsters). Increases the range of Taste Their Fear and Kha'Zix's basic attacks by 50/50/50/50/50.

Array
(
    [0] =>  Array
        (
            [0] => Passive
            [1] => Marks enemies who are isolated from nearby allies.
        )
    [1] =>  Array
        (
            [0] => Active
            [1] => Deals 70/100/130/160/190 (+) physical damage. If the target is isolated, the amount is increased to 100/145/190/235/280 (+).
        )
    [2] =>  Array
        (
            [0] => Evolved Enlarged Claws   
            [1] => Increases damage to isolated enemies by 12/12/12/12/12% of their missing health (max 200/200/200/200/200 vs. monsters). Increases the range of Taste Their Fear and Kha'Zix's basic attacks by 50/50/50/50/50.
        )
)

I can't get past the mid sentence periods.

Upvotes: 1

Views: 153

Answers (3)

kaiser
kaiser

Reputation: 22333

Use . as delimiter for parent/main array and : for sub arrays.

function so12625378_explode_to_multiarray( $string )
{
    foreach ( explode( ". ", $your_string ) as $part )
        $result[] = explode( ": ", $part );

    return $result;
}

Use:

 $string = 'Passive: Marks enemies who are isolated from nearby allies. Active: Deals 70/100/130/160/190 (+) physical damage. If the target is isolated, the amount is increased to 100/145/190/235/280 (+).';
 echo '<pre>'.var_export( so12625378_explode_to_multiarray( $string ), true ).'</pre>';

Upvotes: 0

Patrick
Patrick

Reputation: 1827

(?:^|\s*)([^.:]+):\s*(.+?\.)(?=[\w\s]+:|$)

Name is in capture group 1, description is in capture group 2

Upvotes: 2

raina77ow
raina77ow

Reputation: 106385

Well, this seems to do the trick...

preg_match_all('/(?<=^|[.] )([^:]+): (.+?[.])(?=[^.]+:|$)/', $text, $matches, PREG_SET_ORDER);
var_dump($matches);

... if I understood the structure given ('Term: Description. Term: Description', etc). It's actually colons within Description that might break it; dots do just fine here.

The result of this match can be quite easily transformed into an associative array:

$spell = array();
foreach ($matches as $match) {
   $spell[$match[1]] = $match[2];
}

Upvotes: 1

Related Questions