[英]php regular expression breaks
我在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>"}]);
我想从字符串中找到src和Publisher_id。
为此,我尝试以下代码
$regex = '#\BookSelector.load\(.*?src=\"(.*?)\"}]\)#s';
preg_match($regex, $html, $matches);
$match = $matches[1];
但它始终返回null。
我只选择src的正则表达式是什么?
如果我需要解析BookSelector.load()之间的整个字符串,我的正则表达式将是什么?
首先,我将回答为什么您的正则表达式无法正常工作:
您在正则表达式中使用\\B
它匹配任何与单词边界( \\b
)不匹配的位置,这不是您想要的。 此条件失败,并导致整个正则表达式失败。
您的原始文本包含转义的引号,但您的正则表达式不考虑这些引号。
将此任务分为几个部分,并使用现有最佳工具一一解决。
您需要的数据封装在JSON结构中。 因此,显然,第一步是提取JSON内容。 为此,您可以使用正则表达式。
拥有JSON内容后,您需要对其进行解码以获取其中的数据。 PHP为此具有内置函数: json_decode()
。 将其与输入字符串一起使用,并将第二个参数设置为true
,您将拥有一个不错的关联数组。
一旦有了关联数组,就可以轻松获取包含<script>
标签内容的payload
字符串。
如果您完全确定属性的顺序将始终相同,则可以使用正则表达式提取所需的信息。 如果不是这样,最好使用HTML解析器(例如PHP的DOMDocument)来执行此操作。
整个代码如下:
// 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"
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.