tags:

views:

34

answers:

1

Hi,

I'm still learning PHP Regex so I'm hoping someone can help me with what I'm trying to accomplish.

$string = 'Writing to tell you that var MyCode = "dentline"; Learn it.';

What I'd like to do is match the part of the string which reads

var MyCode ="

After I match that part, I want to retrieve the rest of the dynamically generated characters that follow that string. In this example, [dentline] is 8 characters, but this may not always be the case. Therefore, I want to match all the way until I reach

";

After I've effectively captured that part of the string, I want to strip the string so the remaining information is what lies between the double quotes

dentline

Any help is much appreciated!

+7  A: 

Try this:

$string = 'Writing to tell you that var MyCode = "dentline"; Learn it.';
$matches = array();
preg_match('/var MyCode = "(.*?)";/', $string, $matches);
echo $matches[1];

Result:

dentline

ideone

Explanation

var MyCode = "    Match this string literally and exactly
(                 Start a capturing group.
.*?               Match any characters, as few as possible (not greedy)
)                 End the capturing group.
";                Match the closing double quote followed by a semi-colon

The capturing group "captures" the contents of the match and stores it in the array $matches so that it can be accessed afterwards.

More information about these constructs can be found here:

Variations

If "MyCode" can vary then use this instead:

preg_match('/var \w+ = "(.*?)";/', $string, $matches);

In this expression \w means "match any word character". You might also want to use \s+ instead of a space so that you can match one or more of any whitespace characters (also tab and new line). Similarly \s* matches zero or more whitespace. So another possibility for you to try is this:

preg_match('/var\s+\w+\s*=\s*"(.*?)"\s*;/', $string, $matches);
Mark Byers
Amazing, thankyou! Can you give any further information as to how and why this works?
Dave Kiss
@Dave Kiss: Does my updated answer help?
Mark Byers
I couldn't have asked for anything more, truly, a great resource. Thanks!
Dave Kiss