从string中提取特定值作为不同的变量

时间:2014-12-23 08:26:15

标签: php

我正在尝试提取并将CEO,董事长和任何其他关键职位的值分配给不同的变量。我想知道如何做到这一点以及使用的最佳方法是什么。请参阅下面的代码,其中有一个变量$ keypeople但我希望将其进一步细分为变量$ CEO; $ Chairman等取决于$ keypeople中包含的角色。在下面的示例中,$ keypeople变量返回以下字符串:

key_people = {{unbulleted list|[[Larry Page]] ([[CEO]])|[[Eric Schmidt]] ([[Chairman]])|[[Sergey Brin]] (Director of [[Google X]] and Special Projects){{cite web|url=https://www.google.co.uk/intl/en/about/company/facts/management/ |title=Management Team - Company - Google}}}} 

非常感谢任何帮助。

<html>
<body>
<h2>Search</h2>
<form method="post">
Search: <input type="text" name="q" value="Google"/>
<input type="submit" value="Submit">
</form>

<?php
if (isset($_POST['q'])) {
$search = $_POST['q'];
$search = ucwords($search);
$search = str_replace(' ', '_', $search);
$url_2 = "http://en.wikipedia.org/w/api.php?
action=query&prop=revisions&rvprop=content&format=
json&titles=$search&rvsection=0&continue=";
$res_2 = file_get_contents($url_2);
$data_2 = json_decode($res_2);

?>

<h2>Search results for '<?php echo $search; ?>'</h2>

<?php foreach ($data_2->query->pages as $r): 

?>


<?php foreach($r->revisions[0] as $a); 

if (preg_match_all('/key_people += (.*)/', $a, $result)) {

$keypeople = trim($result[0][0]);

echo $keypeople;
} else {
echo 'Not found';
}

?>

<?php endforeach;

?>

<?php 
}
?>

</body>
</html>

1 个答案:

答案 0 :(得分:1)

$people = array();
$split = explode('|', $keypeople);
foreach ($split as $str) {
    if (preg_match('/\[\[([^]]+)\]\] \(([^)]+)\)/', $str, $match)) {
        $people[str_replace(array('[[', ']]'), '', $match[2])] = $match[1];
    }
}
var_dump($people);

正则表达式匹配模式为[[name]] (role)的任何内容。

输出:

array(3) {
  ["CEO"]=>
  string(10) "Larry Page"
  ["Chairman"]=>
  string(12) "Eric Schmidt"
  ["Director of Google X and Special Projects"]=>
  string(11) "Sergey Brin"
}