查找字符串中的第一个字符串,然后获取匹配的引号之间的所有内容

Find the first string in a string then get everything between quotes where it matches

希望标题有意义,我试过了。

我想做的是找到字符串中特定字符串的第一次出现,然后当我找到该匹配项时,获取匹配项所在的两个双引号之间的所有内容。

例如:

假设我正在尝试在以下字符串中找到第一次出现的“.mp3”

那么我的主串是这样的

我的字符串实际上是 HTML 来自 $string = file_get_contents('http://www.example.com/something') FYI

$string = 'something: "http://www.example.com/someaudio.mp3?variable=1863872368293283289&and=someotherstuff" that: "http://www.example.com/someaudio.mp3?variable=jf89f8f897f987f&and=someotherstuff" this: "http://www.example.com/someaudio.mp3?variable=123&and=someotherstuff" beer: "http://www.example.com/someaudio.mp3?variable=876sf&and=someotherstuff"';

此时,我想找到第一个 .mp3,然后我需要整个 url 位于匹配的双引号内

输出应该是

http://www.example.com/someaudio.mp3?variable=1863872368293283289&and=someotherstuff

我已经知道如何使用 strpos 在 php 中找到匹配项,问题是如何从那里获取引号之间的整个 url?这甚至可能吗?

有几种方法可以做到这一点。使用 strpos (以及其他几个字符串操作函数)就是其中之一。正如您提到的,单独使用 strpos 只会让您进入第一个“.mp3”。所以你需要将它与其他东西结合起来。来玩一玩吧:

$str = <<<EOF
something: "http://www.example.com/someaudio.mp3?variable=1863872368293283289&and=someotherstuff"
that: "http://www.example.com/someaudio.mp3?variable=jf89f8f897f987f&and=someotherstuff"
this: "http://www.example.com/someaudio.mp3?variable=123&and=someotherstuff"
beer: "http://www.example.com/someaudio.mp3?variable=876sf&and=someotherstuff"
EOF;

$first_mp3_location = strpos($str, ".mp3");
//Get the location of the start of the first ".mp3" string
$first_quote_location = $first_mp3_location - strpos(strrev(substr($str, 0, $first_mp3_location)), '"');
/*
 * Working backwards, get the first location of a '"',
 * then subtract the first location of the ".mp3" from that number
 * to get the first location of a '"', the right way up.
 */
$first_qoute_after_mp3_location = strpos($str, '"', $first_mp3_location);
//Then finally get the location of the first '"' after the ".mp3" string

var_dump(substr($str, $first_quote_location, $first_qoute_after_mp3_location - $first_quote_location));
//Finally, do a substr to get the string you want.

这是一种相当迟钝冗长的方式来获得你需要达到的目标,你可能最好使用正则表达式,但 一种只使用 strpos 及其伙伴 strrevsubstr.

的方法

您将使用 preg_match 和可选的 $matches 参数。

The regex in question will be something like

$r = '".*\.mp3.*"';

您会注意到,我已经掩盖了 所有 "a url located within double quotes" 可能意味着什么的微妙之处。

$matches 参数的使用可能感觉有点奇怪;它曾经是函数工作的正常方式,现在仍然是在像 C++ 这样的语言中。

$m = [];
if(preg_match($r, $subject_string, $m)){
  $the_thing_you_want = $m[0];
}