php插入preg_match_all数组

标签 php mysql arrays insert short

这是一段代码,用于捕获 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/

相关文章:

php - 关闭 MAMP 中的缓存

php - 使用左连接时,如果出现重复行,如何将一个字段的所有数据放入数组中

C++ 数组大小声明和常量

php - 如何检查非关联数组在 PHP 中是否唯一?

javascript - 使用 Array.map 时嵌套的 Promise,使用 Promise.all 但仍然不起作用

php - 适用于 Linux 的轻量级 IDE

php - 使用 Google reCaptcha 总是显示 'incorrect-captcha-sol'

php - MySQL - 基于另一个查询的查询

php - HTML Editable P 更新 MySQL DB

php - 我在制作mysql和php菜单系统时有点问题