在嵌入式视频代码上使用preg_match来提取其id URL

时间:2016-09-22 05:26:17

标签: php mysql

我将使用表单将嵌入的视频代码输入到表单字段中,以便将其存储到MYSQL数据库中。 iframe滚动,宽度,高度,框架边框和src不应存储在数据库中。如何使用php preg_match函数从嵌入的视频代码中删除iframe滚动,宽度,高度,框架边框和src。我只想要URL id到视频。如何仅存储嵌入视频的链接而不是其所有属性? 这是代码:

<?php
$servername = "localhost";
$username = "root";
$password = "";

// Create connection
$conn = mysqli_connect($servername, $username, $password);

// Check connection
if (!$conn) {
    die("Connection failed: " . mysqli_connect_error());
}

if(!mysqli_select_db($conn,'tutorial'))
{
echo 'Database not selected';
}

$title = test_input($_POST['title']);
$embedded_video = test_input($_POST['embedded_video']);

//I want preg_match to remove, src, iframe scrolling, width, height, and frameborder out of embeded code

if (preg_match(%^(src)"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i",$embedded_video)) {

      //puting the URL of video in database
      $sql = "INSERT INTO person(title,embedded_video) VALUES ('$title', '$embedded_video')";
    }    
  }


if(!mysqli_query($conn, $sql))
{
 echo "Not inserted";
}
else {

 echo "INSERT";

}



function test_input($data) {
  $data = trim($data);
  $data = stripslashes($data);
  $data = htmlspecialchars($data);
  return $data;
}


?>

<!DOCTYPE html>
<html>
<body>

<form method="post" action="<?php echo htmlspecialchars($_SERVER["PHP_SELF"]);?>">
  <input type="text" name="title" >
  <br>
  Embedded video:<br>
  <input type="text" name="embedded_video">
  <br><br>
  <input type="submit" value="Insert">
</form> 


</body>
</html>

1 个答案:

答案 0 :(得分:0)

您可以为preg_match()第三个变量array()。这将匹配存储在第一个索引上,任何部分匹配其他索引。

我认为这将是您的解决方案:

if (preg_match(%^(src)"/\b(?:(?:https?|ftp):\/\/|www\.)[-a-z0-9+&@#\/%?=~_|!:,.;]*[-a-z0-9+&@#\/%=~_|]/i", $embedded_video, $matches)) {

    //puting the URL of video in database
    $sql = "INSERT INTO person(title,embedded_video) VALUES ('" . $title . "', '" . $matches[0] . "')";
}

(在}之后你使用了if statement太多了!)

供进一步参考: http://php.net/manual/en/function.preg-match.php