简体   繁体   中英

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!

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".

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 ) 

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM