Josh Feingold
Josh Feingold

Reputation: 27

PHP Regular Expression - Extract Data

I have a long string, and am trying to extract specific data that is deliminated in that string by specific words.

For example, here is a subset of the string:

Current   Owner  123 Capital    Calculated  

I am looking to extract

123 Capital

and as you can see it is surrounded by "Current Owner" (with a bunch of arbitrary spaces) to the left and "Calculated" (again with arbitrary spaces) to the right.

I tried this, but I'm a bit new at RegEx. Can anyone help me create a more effective RegEx?

preg_match("/Owner[.+]Calculated/",$inputString,$owner);

Thanks!

Upvotes: 1

Views: 2357

Answers (3)

hwnd
hwnd

Reputation: 70750

A character class defines a set of characters. Saying, "match one character specified by the class". Place the dot . and quantifier inside of a capturing group instead and enable the s modifier which forces the dot to span newlines.

preg_match('/Owner(.+?)Calculated/s', $inputString, $owner);
echo trim($owner[1]);

Note: + is a greedy operator, meaning it will match as much as it can and still allow the remainder of the regex to match. Use +? instead to prevent greediness meaning "one or more — preferably as few as possible".

Upvotes: 2

Brian
Brian

Reputation: 4984

Hope this helps, group index #1 is your target:

Owner\s+(\d+\s+\w+)\s+Calculated

You may also want to try a tool like RegExr to help you learn/tinker.

Upvotes: 0

nu11p01n73R
nu11p01n73R

Reputation: 26677

You can use lookarounds as

(?<=Owner)\s*.*?(?=\s+Calculated)

Example usage

$str = "Current Owner 123 Capital Calculated ";
preg_match("/(?<=Owner)\s*.*?(?=\s+Calculated)/", $str, $matches);
print_r($matches);

Will give an output

Array ( [0] => 123 Capital ) 

Upvotes: 0

Related Questions