php inserting preg_match_all array

佐手、 提交于 2019-12-25 07:58:51

问题


this is a code to catch all url in the POST and shorting them then insert each of them in row in mysql ..... but here it is inserting all the url in one row ?? so how can i make it catch the first url then insert it in database then go back for the second one and do the same..???

$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);
}

回答1:


well, "(.*)" in your regex matches everything after it has found the beginning of a url. so if you're expecting multiple urls in one string, or coma separated or what not, they will all be bundled together.

You need to be able to split your input first, and then validate that each element is a valid url before you pick it up for insertion.




回答2:


Here http://php.net/manual/en/function.preg-match-all.php you can read about the 4th parameter of preg_match_all. You can loop over the urls found. I changed the end of your regular expression, so it won't catch the whole line:

$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);
}

Also be careful with SQL injection, and use mysql_real_escape_string when you use user data in your queries.



来源:https://stackoverflow.com/questions/10546842/php-inserting-preg-match-all-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!