Преобразовать фрагмент Python в PHP? - PullRequest
3 голосов
/ 21 июля 2010

Может кто-нибудь перевести мой маленький фрагмент Python на PHP? Я не знаком с обоими языками. (

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

Спасибо за помощь! (

1 Ответ

1 голос
/ 21 июля 2010

Это прямой перевод вышеприведенного кода с «содержимым», заполненным для демонстрационных целей:

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