У меня есть эта строка 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: Как я могу получить значение xxxxxx, которое находится внутри URL-адреса, который находится внутри более крупной строки html?
Используйте \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
http:\/\/www\.example\.com\/static\/(\d+)\/js
Попробуйте это. Захватите захват. Смотрите демоверсию.
$match[0] = 123456
он возвращает 2 элемента в массиве, где первым является полный URL-адрес (ненужный). Есть идеи почему?
match[0] return the match string always.
используйте match[1]
чтобы получить правильную группу
Использование внешнего вида
(?<=http:\/\/www.example.com\/static\/)\d+(?=\/js)
Вы можете использовать php preg_match_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
http://www.example.com/static/
статической частью?