Regular expression match, extracting only wanted segments of string

Posted by Ben Carey on Stack Overflow See other posts from Stack Overflow or by Ben Carey
Published on 2013-10-23T15:50:24Z Indexed on 2013/10/23 15:53 UTC
Read the original article Hit count: 225

Filed under:
|
|

I am trying to extract three segments from a string. As I am not particularly good with regular expressions, I think what I have done could probably be done better...

I would like to extract the bold parts of the following string:

SOMETEXT: ANYTHING_HERE (Old=ANYTHING_HERE, New=ANYTHING_HERE)

Some examples could be:

ABC: Some_Field (Old=,New=123)

ABC: Some_Field (Old=ABCde,New=1234)

ABC: Some_Field (Old=Hello World,New=Bye Bye World)

So the above would return the following matches:

$matches[0] = 'Some_Field';
$matches[1] = '';
$matches[2] = '123';

So far I have the following code:

preg_match_all('/^([a-z]*\:(\s?)+)(.+)(\s?)+\(old=(.+)\,(\s?)+new=(.+)\)/i',$string,$matches);

The issue with the above is that it returns a match for each separate segment of the string. I do not know how to ensure the string is the correct format using a regular expression without catching and storing the match if that makes sense?

So, my question, if not already clear, how I can retrieve just the segments that I want from the above string?

© Stack Overflow or respective owner

Related posts about php

Related posts about regex