我有以下字符串:从字符串获取文本与正则表达式
Apples Bananas Oranges Me 1 2 3 Brother 4 4 5
我需要一个正则表达式来获得我们每个人的苹果,香蕉和桔子号“我和我的兄弟”了。
请帮助我,我在这里完全无能为力。
我有以下字符串:从字符串获取文本与正则表达式
Apples Bananas Oranges Me 1 2 3 Brother 4 4 5
我需要一个正则表达式来获得我们每个人的苹果,香蕉和桔子号“我和我的兄弟”了。
请帮助我,我在这里完全无能为力。
您可能希望像这样的代码:
$string = file('input.txt');
$headers = array();
$results = array();
foreach($string as $i => $line) {
preg_match_all('@(\w+)@', $line, $matches);
if (!$i) {
$headers = $matches[0];
} else {
$name = array_shift($matches[0]);
$results[$name] = array_combine($headers, $matches[0]);
}
}
print_r($results);
这将导致:
Array
(
[Me] => Array
(
[Apples] => 1
[Bananas] => 2
[Oranges] => 3
)
[Brother] => Array
(
[Apples] => 4
[Bananas] => 4
[Oranges] => 5
)
)
大约
$regexp = "/([\w]+) +([\d]+) +([\d]+) +([\d]+)/";
$matches = array();
preg_match($regexp, $yourDataSet, $matches);
根据,如果你使用的是1个长字符串或用换行的字符串,你可以前的最后一个/在正则表达式中添加\ n,使之更加精确。
这是功课?因为你永远不应该做这个IRL。 –
是**我**和**兄弟**硬编码,或者您在寻找更一般的解决方案吗? – McGarnagle
缺少字符串的任何东西?像HTML表格标记?标签? – 2012-05-15 21:43:29