找到字符串中的第一个字符串,然后在引号匹配之间获取所有内容[关闭]

问题描述 投票:0回答:2

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

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

例如:

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

然后我的主要字符串看起来像这样

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

$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,然后我需要在双引号内的匹配所在的整个网址

输出应该是

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

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

php regex simple-html-dom
2个回答
2
投票

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

The regex in question will be something like

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

你会注意到我已经掩盖了“双引号内的网址”可能含义的所有细微之处。

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

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

1
投票

有几种方法可以做到这一点。使用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来做。

© www.soinside.com 2019 - 2024. All rights reserved.