我有这个 html 字符串,其中包含我需要获取的非常具体的 url。
$string = 'Hi, this is a long string,
<br>
some more text, and then suddenly, a script tag!
<script type="text/javascript" src="http://www.example.com/static/123456/js/SiteCatalyst.js"></script>
<p>more text here</p>
<script type="text/javascript" src="http://www.example.com/other.js"></script>
and then, the end...';
问题是,我需要 123456 值,该值恰好位于该字符串内;
由于该值可以(并且将会)在字符串中更改,因此需要对其进行动态解析。我的第一个方法是查找字符串内的所有 url,但如果有很多 url,这可能会太昂贵。
TL;DR:如何获取位于较大 html 字符串内的 url 内的 xxxxxx 值?
最佳答案
使用 \K
在最后打印时忽略先前匹配的字符。
src="http://www.example.com/static/\K\d+(?=\/)
$string = 'Hi, this is a long string,
<br>
some more text, and then suddenly, a script tag!
<script type="text/javascript" src="http://www.example.com/static/123456/js/SiteCatalyst.js"></script>
<p>more text here</p>
<script type="text/javascript" src="http://www.example.com/other.js"></script>
and then, the end...';
preg_match('~src="http://www.example.com/static/\K\d+(?=\/)~', $string, $matches);
echo $matches[0];
输出:
123456
关于javascript - 使用 PHP 从较大字符串中的 URL 获取查询字符串值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27394861/