仅查找字符串的这一部分 PHP
Find only THIS part of the string PHP
我有一个变量 $string,其中包含以下布局:
image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"
我如何定位并设置 thumb: 的 url 到一个新变量,即:
$thumb = 'http://static.web.com/scripts/image.php/44x44/442873.jpg';
但是每次脚本 运行 时拇指 url(以及所有值)都会不同(所以我无法匹配实际 url 的内容).
基本上我需要用到哪些功能:
1) 在整个字符串中搜索 thumb:
2) select 紧跟引号之间的所有内容
3) 将结果存储到变量中(不带“”)
诚然,这个答案很丑陋,但它确实有效。它使用一对explodes (to break apart the string), a foreach (to iterate through the parts), and an str_replace(去掉双引号。
$string = 'image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"';
$array = explode(",\r\n", $string);
$value = "not found";
foreach($array as $entry)
{
if(substr($entry, 0, 5) == "thumb")
{
$parts = explode(": ", $entry);
$value = str_replace('"', '', $parts[1]);
break;
}
}
echo $value;
如果这是结构化数据格式(json、xml)的一部分,那么您最好为所述格式使用解析器。
否则,根据实际提供的信息,一个简单的正则表达式即可:
$string = 'image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"';
preg_match("~thumb: \"(.*)\",~", $string, $matches);
echo $matches[1];
我有一个变量 $string,其中包含以下布局:
image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"
我如何定位并设置 thumb: 的 url 到一个新变量,即:
$thumb = 'http://static.web.com/scripts/image.php/44x44/442873.jpg';
但是每次脚本 运行 时拇指 url(以及所有值)都会不同(所以我无法匹配实际 url 的内容).
基本上我需要用到哪些功能:
1) 在整个字符串中搜索 thumb:
2) select 紧跟引号之间的所有内容
3) 将结果存储到变量中(不带“”)
诚然,这个答案很丑陋,但它确实有效。它使用一对explodes (to break apart the string), a foreach (to iterate through the parts), and an str_replace(去掉双引号。
$string = 'image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"';
$array = explode(",\r\n", $string);
$value = "not found";
foreach($array as $entry)
{
if(substr($entry, 0, 5) == "thumb")
{
$parts = explode(": ", $entry);
$value = str_replace('"', '', $parts[1]);
break;
}
}
echo $value;
如果这是结构化数据格式(json、xml)的一部分,那么您最好为所述格式使用解析器。
否则,根据实际提供的信息,一个简单的正则表达式即可:
$string = 'image: "http://web.com/files/images/442873_large.jpg",
thumb: "http://static.web.com/scripts/image.php/60x60/402813.jpg",
mp3: "http://web.com/files/clip/6240/23121376.mp3",
waveform: "http://web.com/files/wave/23121376-wf.png"';
preg_match("~thumb: \"(.*)\",~", $string, $matches);
echo $matches[1];