我有一个网页,显示一天中更改的名称列表。我还有一个数据库,里面有所有这些名字的列表。
我需要以某种方式在任何特定时间对网页上显示的名称进行搜索,然后将这些名称与数据库中包含的名称进行匹配。这是一种反向查找。
需要显示在网页上找不到的名称。
我该怎么做?
我试图将数据库行中包含的名称解析为一个数组,将网页上的名称解析成另一个数组然后比较这两个数组。
我已经设法正确地解析了它们,但当我尝试比较它们时出现了问题。
请给我指正确的方向:)
<?php
$a = file_get_contents("https://testpage.com/pbx_info2.php");
#find all the names that are contained within '[' and ']'
preg_match_all('^'[(.*?)']^', $a, $matches);
#output all the names into an array
$output = $matches[0];
#remove the '[' and ']' characters and print the contents of the array.
foreach($output as $u) {
$u = str_replace ('[', '', $u);
$u = str_replace (']', '', $u);
print $u;
echo "<br>";
}
$con=mysqli_connect("localhost","test_user","test_pass","test_teaams");
// Check connection
if (mysqli_connect_errno())
{
echo "Failed to connect to MySQL: " . mysqli_connect_error();
}
else
{
echo "<br>Connected!<br>";
}
$sql="SELECT * FROM test_table";
if ($result=mysqli_query($con,$sql))
{
while ($row=mysqli_fetch_row($result))
{
printf (" ".$row[0],$row[1]);
}
// Free result set
$people[0] = mysqli_free_result($result);
$peep = $people[0];
}
$missing = array_intersect($output, $people);
printf ($missing);
mysqli_close($con);
?>
如果要从数组元素中删除方括号,则需要使用foreach
循环中的引用:
#remove the '[' and ']' characters and print the contents of the array.
foreach($output as &$u) {
$u = str_replace ('[', '', $u);
$u = str_replace (']', '', $u);
print $u;
echo "<br>";
}
&$u
完成了这项工作。否则,您将不会在$output
数组中"就地"更改$u
,而是创建了一个新的$u
变量,该变量在循环中每次都会被覆盖。
不必在PHP中比较返回的结果,您可以通过为SELECT
语句创建一个合适的WHERE
条件来过滤数据库中已经存在的表行:
$where=count($output)?"WHERE usrname NOT IN ('".join("','",$output)).')":'';
只有当有个用户ID要匹配时,才会构造WHERE
子句。并将其应用于
$sql="SELECT usrname,col1,col2,col3 FROM test_table $where";
// it is NOT a good idea to use * in SELECT statements since
// a table structure might change over time ...
假定CCD_ 9是具有用户名的列。返回的行应该是您想要的:数据库中不而的条目出现在网站上。
编辑:
如果使用更好的正则表达式,则可以完全避免第一个问题:
preg_match_all('^(?<='[)(.*?)(?='])^', $a, $matches);
(?<='[)
和(?='])
被称为look-behind和look-ahead模式,并且不是匹配字符串的一部分。
请参见此处:https://regex101.com/r/qK4yQ0/1