2

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!

2
  • Will your string always be double quoted, not single quoted? Could your string contain escaped quotes? Are whitespaces significant in the code? Is the variable name always "MyCode" or can it be other names? Commented Oct 4, 2010 at 22:47
  • String is always double quoted. No escaped character, no whitespace, no change in variable name. Just as is. Commented Oct 4, 2010 at 23:48

1 Answer 1

8

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);
Sign up to request clarification or add additional context in comments.

2 Comments

Amazing, thankyou! Can you give any further information as to how and why this works?
I couldn't have asked for anything more, truly, a great resource. Thanks!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.