llanato
llanato

Reputation: 2503

Regex Expression Issue

I have the below regex expression and I'm trying to break it into two parts, there might not always be the the two parts though.

Section Level: Very Low. Type: Animal.

I'm using the below to break it by characters but I need to be able to break by the string, identify the level and type so they can be returned into two separate database columns. For example I need to check the string and see if there is anything matching 'Section Level: {text}.' and insert it into the level column in the database and the same for type, I need to check the string for 'Type: {text}.' and insert it into a type column.

(?<=\:)(.*?)(?=\.)

I've been able to get the first piece out using (\w*)(.*?)(?=\.) but still can't for the life of me get the second part.

Upvotes: 1

Views: 58

Answers (2)

anubhava
anubhava

Reputation: 785701

Following regex should work for you:

(?=\w)(?:Section\s+Level:\s*([^.]+)\.)?\s*(?:Type:\s*([^.]+)\.)?

With both Level and Type fields as optional fields.

Live Demo: http://www.rubular.com/r/GpSHs69YHy

Upvotes: 2

Michael
Michael

Reputation: 12806

I'd probably use strtok rather than regular expressions:

$string = 'Level: Very Low. Type: Animal.';

$parts = array();

for ($s = strtok($string, '.'); $s; $s = strtok('.'))
{

  $array = explode(':', $s);

  $parts[trim($array[0])] = trim($array[1]);

}

print_r($parts);

That would give you:

Array
(
    [Level] => Very Low
    [Type] => Animal
)

The benefit is that if you ever added something else, say Gender: Male then you wouldn't have to modify the code (much).

Upvotes: 1

Related Questions