这是一段代码,用于捕获 POST 中的所有 url 并缩短它们,然后将它们插入到 mysql 的行中......但这里是将所有 url 插入一行? 那么我怎样才能让它捕获第一个网址,然后将其插入数据库,然后返回第二个网址并执行相同的操作..???
$urlinput=mysql_real_escape_string($_POST['url']);
$pattren="/(http:\/\/)[a-zA-Z0-9]*\.[a-z]*(.*)|(www)\.[a-zA-Z0-9]*\.[com]*(.*)/";
preg_match_all( $pattren, $urlinput, $matches );
foreach($matches[0] as $match) {
$id=rand(10000,99999);
$shorturl=base_convert($id,20,36);
$sql = "insert into url values('$id','$match','$shorturl')";
mysql_query($sql,$con);
}
最佳答案
这里http://php.net/manual/en/function.preg-match-all.php你可以阅读 preg_match_all 的第四个参数。您可以循环查找找到的网址。我更改了正则表达式的结尾,因此它不会捕获整行:
$urlinput=mysql_real_escape_string($_POST['url']);
$pattren="/(http:\/\/)[a-zA-Z0-9]*\.[a-z]*(.*)|(www)\.[a-zA-Z0-9]*\.[com]*([a-zA-Z0-9\.\-_\/\?=\:]*)/";
preg_match_all( $pattren, $urlinput, $matches, PREG_SET_ORDER );
foreach($matches as $match) {
$id=rand(10000,99999);
$shorturl=base_convert($id,20,36);
$sql = "insert into url values('$id','" . mysql_real_escape_string($match[0]) . "','$shorturl')";
mysql_query($sql,$con);
}
还要小心 SQL 注入(inject),并在查询中使用用户数据时使用 mysql_real_escape_string。
关于php插入preg_match_all数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10546842/