Home > Blockchain >  Extracting a specific keyword from a string
Extracting a specific keyword from a string

Time:03-11

Currently I have a string value that is coming in which looks something like this: I'm interested in the property LP11503. Now here the term I want to extract is LP11503. Basically the term should have LP in the beginning followed by numbers from 0-9.

I've tried using preg_match_all to get the numbers from my string, but this method extracts all the numbers in the string. So basically if the string were to be I'm interested in 2 bedroom property LP11503, it would print out both 2 and 11503. I want it to print LP11503. Here is what I've tried so far which is printing all my numbers in the string:

$data = array(
    'name' => "jay",
    'number'=> '1234',
    'message'=> 'I\'m interested in the property LP11503'
);
preg_match_all('!\d !', $data['message'], $matches);
print_r($matches);

Now how do I only extract the keyword LP[0-9].

CodePudding user response:

You may use the pattern \b[A-Z] [0-9] \b:

$message = "I'm interested in 2 bedroom property LP11503";
preg_match_all("/\b[A-Z] [0-9] \b/", $message, $matches);
print_r($matches[0][0]);  // LP11503

CodePudding user response:

Try this:

preg_match_all('/LP\d /', $data['message'], $matches);
print_r($matches[0][0]);
  • Related