javascript - 使用 PHP 从较大字符串中的 URL 获取查询字符串值

标签 javascript php regex preg-match

我有这个 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 值,该值恰好位于该字符串内;

http://www.example.com/static/xxxxxx/js/SpecificScript.js

由于该值可以(并且将会)在字符串中更改,因此需要对其进行动态解析。我的第一个方法是查找字符串内的所有 url,但如果有很多 url,这可能会太昂贵。

TL;DR:如何获取位于较大 html 字符串内的 url 内的 xxxxxx 值?

最佳答案

使用 \K 在最后打印时忽略先前匹配的字符。

src="http://www.example.com/static/\K\d+(?=\/)

DEMO

$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/

相关文章:

javascript - 三个js PERFORMANCE如何让使用图像纹理更快

php - 允许用户在网站内添加网页

php - 在 laravel 4 上验证上传图片

c# - 何时不在 C#(或 Java、C++ 等)中使用 Regex

MySQL正则表达式用于排除字符串

javascript - 一个 "debug"是如何生成一个 css 文件的

javascript - 在 Adob​​e DTM 中读取 HTML 表 header value

c# - 如何在 C# 中使用正则表达式解析 OData $filter?

javascript - 如何避免将 setState 与回调一起使用

java - 动态网站 build 的信息收集和选择其架构