Javascript 使用PHP从较大字符串内的URL获取查询字符串值

Javascript 使用PHP从较大字符串内的URL获取查询字符串值,javascript,php,regex,preg-match,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

我有这个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...';
$string='您好,这是一个长字符串,

更多的文字,然后突然,一个脚本标签! 这里有更多的文字

然后,结局;
问题是,我需要123456值,它正好在这个字符串中

由于该值可以(也将)在字符串中更改,因此需要对其进行语法分析。我的第一种方法是查找字符串中的所有URL,但是如果有许多URL,那么这可能会太昂贵

TL;DR:如何获取url中的xxxxxx值,该url位于更大的html字符串中

http:\/\/www\.example\.com\/static\/(\d+)\/js
试试这个。抓拍。看演示

使用环顾四周

(?<=http:\/\/www.example.com\/static\/)\d+(?=\/js)

(?使用
\K
在最终打印时忽略先前匹配的字符

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


您可以使用php
preg\u match\u all()
获取一个数字

$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_all('!\d+!', $string, $matches);
echo $matches[0][0]; //output 123456
$string='您好,这是一个长字符串,

更多的文字,然后突然,一个脚本标签! 这里有更多的文字

然后,结局; preg_match_all(“!\d+!”,$string,$matches); echo$matches[0][0];//输出123456
它是否总是存在于src属性中?是否
http://www.example.com/static/
a static part?@AvinashRaj是的,它将始终位于脚本标记内。查看此链接,您可以将文本加载到简单的HTML DOM解析器。然后访问标记,您可以分离所需内容。这将获得所有数字,而不仅仅是我正在查找的数字ng。这是一种工作方式。它不只是返回
$match[0]=123456
而是返回数组中的两个项目,其中第一个是完整的url(不必要)。知道为什么吗?@andufo
match[0]总是返回匹配字符串。
使用
match[1]
使用PHP Javascript从较大字符串中的URL获取正确的groupGet querystring值不支持查找。但OP需要PHP
123456
$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_all('!\d+!', $string, $matches);
echo $matches[0][0]; //output 123456