将一个Python代码片段转换为PHP?

3

有人能将我的小 Python 代码片段翻译成 PHP 吗?我对这两种语言都不太熟悉 :(

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

感谢那些提供帮助的人!:(

“print totalrewards” 打印出结果的可读解释 - 您是否想对数据进行其他操作?我的答案会进行类似的人类可读转储,但格式不完全相同 - 这符合您的需求吗? - Shabbyrobe
是的,我希望它列出所有的结果 :( - Tank Stalker
1个回答

1

这是上面代码的直接翻译,其中“contents”已填充以进行演示:

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

顺便提一下,如果您使用上面的代码,Python变量totalrewards相当于$matches [0] [1] - NullUserException
当我运行上面的python代码时,针对'"cap":"foo" "cap":"wahey"'的内容,我的输出结果为['foo', 'wahey']。我在问题下面发布了一条有关所需输出性质的评论,但考虑到“print totalrewards”本质上打印了一个数据结构的可读文本,我认为在纯Python到PHP的翻译中,“var_dump($matches)”是功能上等效的。 - Shabbyrobe
哎呀,我该如何让它列出"foo"和"wahey",像这样:foo wahey 等等 等等我尝试查找var_dump(),但显然我的大脑无法理解如何使用它或它的工作原理xD。如果我有些愚蠢,请原谅。 - Tank Stalker
已更新,以给你所需的输出。 - Shabbyrobe

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接