将Python代码段转换为PHP?

时间:2010-07-21 05:45:40

标签: php python code-snippets

任何人都可以将我的小型Python代码段翻译成PHP吗?我不熟悉这两种语言。 :(

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

感谢那些有帮助的人! :(

1 个答案:

答案 0 :(得分:1)

这是上述代码的直接翻译,其中填充了“内容”用于演示目的:

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

输出:

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

如果您想对结果实际执行某些操作,例如列出来,试试:

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