开发者

Convert a Python snippet to PHP?

开发者 https://www.devze.com 2023-01-08 17:31 出处:网络
Can anyone translate my small Python snippet to PHP? I\'m not a familiar with both languages. :( matches = re.compile(\"\\\"cap\\\":\\\"(.*?)\\\"\")

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)
pr开发者_JS百科int totalrewards

Thank you for those who'd help! :(


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";
    }
}
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号