0

I grab the source code of a website with file_get_contents(). Inside this code, i try to detect this king string and put the content of idDM in a variable.

'idDM':'x1mi7f7'

For example, here, $idDM will be equal to x1mi7f7, but the string can be :

'idDM':'xxxxxxx'

And the variable will be xxxxxxx.

I know o have to use REGEX for that. For now, I just manage to find if there is IdDM, but not to recover its contents.

Any advice ? Thanks.

1
  • If the file you get has a Json-like format, it is probably easier to use json-decode (after little modification if needed). Commented Apr 7, 2014 at 13:51

1 Answer 1

3

Use the following regex:

'idDM'\s*:\s*'([^']+)'

Explanation:

  • 'idDM' - match the literal string 'idDM' (with the quotes)
  • \s* - match one or more whitespace character
  • : - match a literal colon character
  • \s* - match one or more whitespace character
  • '([^']+)' - match (and capture) everything that's inside single-quotes

Usage:

$str = "foo bar 'idDM':'x1mi7f7' more baz";

if (preg_match("/'idDM'\s*:\s*'([^']+)'/", $str, $matches)) {
    $idDM = $matches[1];
}

var_dump($idDM); // => string(7) "x1mi7f7"

Demo

Sign up to request clarification or add additional context in comments.

3 Comments

Thanks fo your answer and the explanation. It's really perfect !
@artmees: That's not really needed in this case as the variable will get initialized inside the if block if a match is found. Plus, the idDM part seems to be constant, so I don't see the reason to use variable-variables here.
@AmalMurali thanks i thought he needed to add it to a variable :D mybad

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.