PHP:在字符串中的特定单词后提取特定单词?

时间:2015-10-27 15:22:24

标签: php

我有一个看起来像这样的字符串:

{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}

我只需要该字符串中country_name的值。

所以我尝试了这个:

$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';

if (preg_match('#^country_name: ([^\s]+)#m', $country, $match)) {
    $result = $match[1];
}

echo $result;

$result

中没有任何回应

有人可以就此问题提出建议吗?

4 个答案:

答案 0 :(得分:5)

$country = json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}');

echo $country->country_name;

你有一个JSON字符串。

JSON代表JavaScript Object Notation。 PHP可以通过json_decode($ string,FALSE)将其解码为数组或对象;

默认情况下,第二个参数为FALSE,这意味着它会将字符串转换为一个对象,然后您可以按照我上面的显示进行访问。

答案 1 :(得分:1)

如果由于某种原因您不想使用JSON,您可以试试以下内容。请注意,使用JSON是执行此任务的推荐方法。

text()

结果:

$country = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';

$temp = explode('"country_name":', $country); //Explode initial string
$temp_country = explode(',', $temp[1]); //Get only country name
$country_name = str_replace('"', ' ', $temp_country[0]); //Remove double quotes
echo $country_name;

答案 2 :(得分:0)

试试这个:

<?php
$country=json_decode('{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}')
$result=$country->country_name;
echo $result;
?>

答案 3 :(得分:0)

这看起来像一个json字符串。详细了解JSON

像这样使用:

$foo = '{"ip":"XX.XX.XX","country_code":"IE","country_name":"Ireland","region_code":"L","region_name":"Leinster","city":"Dublin","zip_code":"","time_zone":"Europe/Dublin","latitude":53.333,"longitude":-6.249,"metro_code":0}';
$bar = json_decode($foo, true);
echo $bar['country_name'];

这可以与该字符串中的任何key一起使用(例如ipcity

有关json_decode的更多信息。