2010-07-21 61 views
3

任何人都可以将我的小Python代码片段转换为PHP吗?我对这两种语言都不熟悉。 :(将Python片段转换为PHP?

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

谢谢你对那些谁愿意帮助:(

+0

'print totalrewards'打印结果的人类可读解释 - 您是否正在寻找其他数据?我的答案做了一个类似人类可读的转储,但它的格式不完全相同 - 是您需要的吗? – Shabbyrobe 2010-07-21 05:52:25

+0

是的,我想要它列出所有的结果:( – 2010-07-21 06:10:28

回答

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

顺便说一句,如果你使用上面的代码,Python变量'totalrewards'相当于'$ matches [0] [1]' – NullUserException 2010-07-21 05:52:58

+0

当我运行上面的python代码对于'cap'的内容:“foo”“cap”:“wahey”',我得到['foo','wahey']作为输出结果。我发布了关于所需输出性质问题的评论,但考虑到“print totalrewards”基本上打印了一个数据结构的可读取转储文件,我认为“var_dump($ matches)”在纯Python到PHP转换中的功能是等价的。 – Shabbyrobe 2010-07-21 05:56:56

+0

嗯,我将如何使它能够列表在 “富” 和 “wahey”,如: 富 wahey 等 等 我试图寻找向上的var_dump(),但apparen我的头脑无法理解如何使用它或它如何工作xD 对不起,如果我有点愚蠢 – 2010-07-21 05:58:00