从字符串 php 中提取一些数据

Extract some data from string php

快速提问,轻松截断字符串。我知道 substr 但我不能在我的情况下使用它。

例如,我有这条丁字裤:“1 rue Maryse Bastie 69500 BRON” 在这种情况下,我想说 "Get all the end before the numbers" "BRON" 并获取数字。我想要差异变量中的城市和邮政编码。

API 我正在使用 returns 完整地址,但我想剪掉以将城市和邮政编码保存在不同的 table.

我认为这个主题可以帮助我:Extracting a zip code from an address string但不能得到城市。

例如,如果我有 1 rue Maryse Bastie 69500 BRON 我想要 $city = "BRON" 和 $pc = "69500"

如果我有13 rue Hohwald 67000 Strasbourg 我想要 $city = "Strasbourg" 和 $pc = "67000"

谢谢

我给你一个解决方法,它应该完全有效,但也许你需要改进它:

$test = '1 rue Maryse Bastie 69500 BRON';
\preg_match('/\b\d{4,5}.+$/i', $test, $out);
$output = \explode(' ', \trim($out[0]), 2);
var_dump($output);
/*
array(2) {
  [0]=>
  string(5) "69500"
  [1]=>
  string(4) "BRON"
}
*/

在上面的代码中,我们使用正则表达式以这种方式查找:

  • 查找数字(很多字符 --> 4 或 5 5 代表法国邮政编码)
  • 找到邮政编码后面的所有字符,直到结尾

接下来我们去掉开头和结尾的空格,然后拆分成一个数组。

如果您获得的字符串格式与您在问题中提到的格式相同,您可以将字符串分解为一个数组并收集最后两个元素作为您需要的值。

让我告诉你。

$myString = "1 rue Maryse Bastie 69500 BRON";
$breakUP = explode(" ", $myString);
$totalElement = count($breakUP);
$city = $breakUP[$totalElement - 1]; // Last element
$zip = $breakUP[$totalElement - 2]; // Second Last element

希望对您有所帮助:)