3

Can anyone translate my small Python snippet to PHP? I'm not a familiar with both languages. :(

matches = re.compile("\"cap\":\"(.*?)\"")
totalrewards = re.findall(matches, contents)
print totalrewards

Thank you for those who'd help! :(

2
  • print totalrewards prints a human-readable interpretation of the result - are you looking to do something else with the data? My answer does a similar human-readable dump, but it's not in exactly the same format - is that what you need? Commented Jul 21, 2010 at 5:52
  • yes i wanted it to list all the result :( Commented Jul 21, 2010 at 6:10

1 Answer 1

1

This is a direct translation of the code above, with "contents" populated for demonstration purposes:

<?php
$contents = '"cap":"foo" "cap":"wahey"';
if (preg_match_all('/"cap":"(.*?)"/', $contents, $matches, PREG_SET_ORDER)) {
    var_dump($matches);
}

The output:

array(2) {
  [0]=>
  array(2) {
    [0]=>
    string(11) ""cap":"foo""
    [1]=>
    string(3) "foo"
  }
  [1]=>
  array(2) {
    [0]=>
    string(13) ""cap":"wahey""
    [1]=>
    string(5) "wahey"
  }
}

If you want to actually do something with the result, for e.g. list it, try:

<?php
$contents = '"cap":"foo" "cap":"wahey"';
if (preg_match_all('/"cap":"(.*?)"/', $contents, $matches, PREG_SET_ORDER)) {
    foreach ($matches as $match) {
        // array index 1 corresponds to the first set of brackets (.*?)
        // we also add a newline to the end of the item we output as this
        // happens automatically in PHP, but not in python.
        echo $match[1] . "\n";
    }
}
Sign up to request clarification or add additional context in comments.

4 Comments

By the way the Python variable totalrewards is equivalent to $matches[0][1] if you use the code above.
When I run the python code above for a contents of '"cap":"foo" "cap":"wahey"', I get ['foo', 'wahey'] as the output. I posted a comment on the question about the nature of required output, but considering "print totalrewards" essentially prints a human-readable dump of a data structure, I consider "var_dump($matches)" to be functionally equivalent in a pure Python to PHP translation.
um how will I be able to make it list the "foo" and "wahey" like: foo wahey etc etc i tried looking up var_dump() but apparently my mind can't comprehend how to use it or how it works xD sorry if i'm being somewhat dumb
Updated again to give you the output you wanted.

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.