【发布时间】:2017-05-07 03:48:18
【问题描述】:
我有一个包含 html 代码的 txt 文件。我正在尝试创建一个 PHP 页面来搜索代码并为我获取“用户名”:
这是页面的一个小示例:
<div class="search-result-details">
<div class="employee-name">This is my name!</div>
<ul class="employee-details">
<li><span class="label">Login</span>username</li>
<li><span class="label">Employee ID</span>####</li>
<li><span class="label">Barcode ID</span>###</li>
<li><span class="label">Status</span>Active</li>
</ul>
<ul class="org-details">
<li><span class="label">Location</span>SAT1 (755)</li>
<li><span class="label">Shift</span>AAAA</li>
<li><span class="label">Department</span>1231</li>
<li><span class="label">Area</span>26</li>
<li><span class="label">Crew</span>0</li>
<li><span class="label">Supervisor</span>manager name</li>
</ul>
</div>
</a></li>
</ol>
</div>
我需要从以下行获取用户名:
<li><span class="label">Login</span>username</li>
我已经有了这个,至少可以抓住我需要的线:
<?php
$file = 'log.txt';
$searchfor = '<ul class="employee-details">
<li><span class="label">Login</span>';
// the following line prevents the browser from parsing this as HTML.
header('Content-Type: text/plain');
// get the file contents, assuming the file to be readable (and exist)
$contents = file_get_contents($file);
// escape special characters in the query
$pattern = preg_quote($searchfor, '/');
// finalise the regular expression, matching the whole line
$pattern = "/^.*$pattern.*\$/m";
// search, and store all matching occurences in $matches
if(preg_match_all($pattern, $contents, $matches)){
echo "Found matches:\n";
echo implode("\n", $matches[0]);
}
else{
echo "No matches found";
}
?>
电流输出:
<ul class="employee-details">
<li><span class="label">Login</span>username</li>
非常感谢任何帮助。谢谢。
【问题讨论】:
-
我更喜欢用 DOMDocument 和 DOMXpath 解析 HTML 文件,也许它也是你的