我开始学习php。我有一个数组:
array (size=24)
0 => string 'Paris, 458 boulevard Saint-Germain' (length=34)
1 => string 'Paris, 343 boulevard Saint-Germain' (length=35)
2 => string 'Marseille, 343 boulevard Camille Flammarion' (length=44)
3 => string 'Marseille, 29 rue Camille Desmoulins' (length=37)
4 => string 'Marseille, 1 chemin des Aubagnens' (length=34)
5 => string 'Paris, 12 rue des singes' (length=25)
6 => string 'Paris, 34 quai VoLtAiRe' (length=24)
7 => string 'Paris, 34 rue Voltaire' (length=23)
8 => string 'Lille, 120 boulevard Victor Hugo' (length=33)
9 => string 'Marseille, 50 rue Voltaire' (length=27)
10 => string 'Toulouse, 90 rue Voltaire' (length=26)
...
我想做的是将每个字符串元素解析为var:
$city = Lyon, Paris, Marseille...
$Number = 458, 343, 29..
$typeOfRoad = boulevard, rue, chemin, quaie...
$NameOfRoad = Saint-Germain, Camille Flammarion...
[编辑]感谢@ splash58,我解决了我的问题!非常感谢你!
感谢。 :)
答案 0 :(得分:2)
foreach($input as $item) {
// Parse string
if (preg_match('/^(?P<city>\w+),\s+(?P<Number>\d+)\s+(?P<typeOfRoad>\w+)\s+(?P<NameOfRoad>.+)$/', $item, $m));
// remove numerous keys
$m = array_diff_key($m, array_flip(range(0,4)));
// make vars
extract($m);
echo "$city $Number $typeOfRoad $NameOfRoad\n";
}
答案 1 :(得分:0)
试试这段代码:( $ array是包含所有项目的数组)
<?php
foreach ($array as $item) {
/* explode in 4 segments max */
$segment = explode(' ', $item, 4);
$city = $segment[0];
$number = $segment[1];
$typeOfRoad = $segment[2];
$nameOfRoad = $segment[3];
/* here you can use the variables before the next loop */
[...]
}
?>
编辑:此代码假设第一个,第二个和第三个变量没有空格,否则它对分隔符不可能。
答案 2 :(得分:0)
$string = 'Lille, 120 boulevard Victor Hugo';
echo $city = substr($string, 0, strpos($string, ','));
echo PHP_EOL;
$parts = explode(" ", $string);
array_shift($parts);
echo $num = $parts[0];
echo PHP_EOL;
array_shift($parts);
echo $type = $parts[0];
echo PHP_EOL;
array_shift($parts);
echo $roadName = implode($parts, " ");
echo PHP_EOL;
答案 3 :(得分:-1)