0

I need to extract id and name from the following string.

$string = $data[1][0];

preg_match('/NAME\s+:([^ID]+)(ID\s+:)(.+)/', $string, $matches);

print_r($matches);

The above expression works when I have tried online tools but it's not working in the script only when getting value from the array.

String value is

$string = 'NAME      : KARL JOHNSON ID        : 12345 (LGW FA-319,320 ) ';
12
  • 3
    This is never going to work (at least not reliably) - someone could literally be called ID: if they wanted. Commented Jul 31, 2018 at 15:25
  • aren't there some hidden \n in the string? With this string you can't really tell what's a key and what's a value. Commented Jul 31, 2018 at 15:26
  • if you are sure the format will always be as in your example, why not splice the content after the colons, stopping at any double space? Commented Jul 31, 2018 at 15:29
  • 1
    see Commented Jul 31, 2018 at 15:39
  • 1
    [^ID]+ probably does not do what you expect. It's a negated character class and matches characters that are neither I nor D. To find the culprit please show the exact data that fails, as your sample data is actually working with your code. Here is another regex idea. Commented Jul 31, 2018 at 15:44

2 Answers 2

1

As mentioned in comments by @CD001 this could never work, but here is pattern that may satisfy your needs:

NAME +: +([a-zA-Z ]+)ID +: *(.+)

First captured group is the name, second is the ID.

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

It works fine but when I fetch the same value as sample data from an array it gives me an empty array. Not sure whats going wrong.
Did you try looping through array and matching one element at a time?
I fetched the value from the array and I did print and make sure it is the same as sample data. As it is the only value.
0

Here's my attempt:

preg_match('/NAME\s+: ([A-Z ]+) ID\s+: ([0-9]+ )\([A-Z0-9 \-,]+\)/', $string, $matches);

$name = $matches[1];
$id = $matches[2];

The complete output:

echo '<pre>' . print_r($matches, true) . '</pre>';

Array
(
    [0] => NAME      : KARL JOHNSON ID        : 12345 (LGW FA-319,320 )
    [1] => NAME      : 
    [2] => KARL JOHNSON
    [3] =>  ID        : 
    [4] => 12345 
    [5] => (LGW FA-319,320 )
)

This may not be optimized, I'm training on RegEx actually.

2 Comments

Your solution only gives me ID but name contains the ID word
Sorry, misunderstood !

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.