0

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
  • what's your input look like? What is between the urls? spaces? new lines? Commented May 11, 2012 at 7:29

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You might want to check the documentation for preg_match_all(): elements of $matches correspond to each parenthesised subpattern (except $matches[0] which are the full pattern matches).
0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.