2014-04-23 71 views
0

我從一個陣列的比賽

一些字符串可能包含多個URL等字符串可能只是簡單的文本

如果字符串包含1個或多個字符串中搜索網址PHP檢查的preg_match那麼我想寫的URL只存儲他們在表中的網址。

否則,如果只包含文本,我還是想存儲在表中的文本。

這是我到目前爲止嘗試過的。

  $urlList = $urlArrayVal[0]; //String within array 
      $regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i'; 
      preg_match_all($regex, $urlList, $matches); 
      $urls = $matches[0]; 
      var_dump($urls); 
      // go over all links 
      foreach($urls as $url) { 
       $sql = "INSERT INTO urls (url) VALUES ('$urls')"; 
       mysqli_query($link, $sql); 
      } 

我現在卡住了。這隻會將URLS(如果有的話)寫入表中,忽略具有純文本的字符串。

任何幫助appreaciated

編輯:另外,如果一個字符串已經超過1個URL,我想所有的URL存儲在一個字符串,一列在表中。

+1

計數匹配的數量,如果沒有,添加純文本。 – Halcyon

+0

@doge感謝,我把你的建議,我設法解決我的問題 – Joe

回答

1

使用preg_match_all,而不是整個數組:

$sql="INSERT INTO urls (url) VALUES "; 
for($i=0; $i<count($urlList), $i++) 
{ 
$numMatches=preg_match_all($regex, $urlList[$i], $matches, PREG_PATTERN_ORDER); 
if(!$numMatches) 
{ 
    //handle the error 
} 
else if($numMatches==0) 
{ 
    //no url's found 
    //save $urlList[$i] (the string) somewhere if you want 
} 
else if($numMatches>0) 
{ 
    //found urls, append them in the query 
    for($j=0;$j<count($matches[0]);$j++) 
    $sql.=" ('".$matches[0][$j]."')," 
} 
else 
{ 
    //this shouldn't happen 
}  
} 
rtrim($sql, ",")//remove the last comma from the query 
mysqli_query($link, $sql); 
1

如果我使用這一切都將工作:

<?php 
$urlList = 'something 
something and http://www.url.com and so on 
and 2 http://www.3url.com or http://www.2url.com in a row'; 
$regex = '/\b(https?|ftp|file):\/\/[-A-Z0-9+&@#\/%?=~_|$!:,.;]*[A-Z0-9+&@#\/%=~_|$]/i'; 
preg_match_all($regex, $urlList, $matches); 
$urls = $matches[0]; 
var_dump($urls); 
// go over all links 
foreach($urls as $url) { 
    echo$sql = "INSERT INTO urls (url) VALUES ('$url')"; 
    mysqli_query($link, $sql); 
} 
?> 

你必須讓我們一個例子字符串更好的測試,您的問題。每個串

+0

您的字符串的例子是正確的 – Joe

+0

不過,我想這個早期的教(它的工作原理),但如果字符串已超過1個URL,就會將它們插入到不同的行。 – Joe

+0

我設法修復它。 – Joe