php正则表达式中断
我在html中有以下字符串php正则表达式中断,php,regex,Php,Regex,我在html中有以下字符串 BookSelector.load([{"index":25,"label":"Science","booktype":"pdf","payload":"<script type=\"text\/javascript\" charset=\"utf-8\" src=\"\/\/www.192.168.10.85\/libs\/js\/books.min.js\" publisher_id=\"890\"><\/script>"}]); 但它总
BookSelector.load([{"index":25,"label":"Science","booktype":"pdf","payload":"<script type=\"text\/javascript\" charset=\"utf-8\" src=\"\/\/www.192.168.10.85\/libs\/js\/books.min.js\" publisher_id=\"890\"><\/script>"}]);
但它总是返回空值
我的正则表达式只选择src是什么
如果我需要解析BookSelector.load()之间的整个字符串,我的正则表达式是什么 为什么你的正则表达式不起作用?
首先,我将回答您的正则表达式不起作用的原因:
\B
。它匹配任何与单词边界不匹配的位置(\b
),这不是您想要的。此条件失败,并导致整个正则表达式失败
true
,您将拥有一个很好的关联数组
有效负载
字符串,其中包含
标记内容
// Extract the JSON string from the whole block of text
if (preg_match('/BookSelector\.load\((.*?)\);/s', $text, $matches)) {
// Get the JSON string and decode it using json_decode()
$json = $matches[1];
$content = json_decode($json, true)[0]['payload'];
$dom = new DOMDocument;
$dom->loadHTML($content);
// Use DOMDocument to load the string, and get the required values
$script_tag = $dom->getElementsByTagName('script')->item(0);
$script_src = $tag->getAttribute('src');
$publisher_id = $tag->getAttribute('publisher_id');
var_dump($src, $publisher_id);
}
输出:
string(40) "//www.192.168.10.85/libs/js/books.min.js"
string(3) "890"
src=
和“
引号之间有一个反斜杠,它在PHP字符串和正则表达式中转义不足,无法作为文本反斜杠进行匹配。为什么要转义B
和”
?原始输入中是否包含反斜杠?删除字符串中除JSON语法部分以外的所有内容并使用JSON\u decode()
将其计算为数组会更容易。更合理的做法是:\BookSelector.load\(.*src=\\\\”(.*?\\”
string(40) "//www.192.168.10.85/libs/js/books.min.js"
string(3) "890"