alekstrust
alekstrust

Reputation: 185

Regular expression to capture this text from a list

The text I have:

URL: http://example.com
Type: department
Empty value:
Contact Name: John Doe
...

I want to get an array like this:

array(
  'url'           => 'http://example.com',
  'type'          => 'department',
  'empty-value'   => '',
  'contact-mame'  => 'John Doe'
)

I was doing something like

preg_match_all( '/(url|type): (.*)/i', $string, $match );

But $match doesn't have the values in the order I need and I don't know how to capture the keys.

The conversion to lowercase keys and dashes doesn't matter at this time.

Can you suggest any regex pattern?

Thank you very much.

Upvotes: 1

Views: 20

Answers (1)

anubhava
anubhava

Reputation: 785256

You can use preg_match_all and array_combine:

$s = <<< EOF
URL: http://example.com
Type: department
Empty value:
Contact Name: John Doe
EOF;

preg_match_all('~^([^:]+):\h*(.*)$~m', $s, $matches);
$output = array_combine ( $matches[1], $matches[2] );
print_r( $output );

Output:

Array
(
    [URL] => http://example.com
    [Type] => department
    [Empty value] =>
    [Contact Name] => John Doe
)

Upvotes: 2

Related Questions