2017-11-04 74 views
0

我有幾個網址在我的數據庫,它是這樣:喜歡的東西SQL 「LIKE」,但在PHP

ID網址

1 http://test.com/embed-990.html 
2. http://test2.com/embed-011.html 
3. http://test3.com/embed-022.html 

我怎麼能如果URL中的一個做一個簡單的PHP代碼沒有按數據庫中不存在,只是加載另一個?我需要通過域來檢查這些網址。

例如是這樣的:

if($data['url'] == "test.com") { 
echo "my embed code number 1"; 
} elseif($data['url'] == "test2.com") { 
echo "my another embed code"; 
} 

回答

2

可以parse the URL獲取主機,然後進行比較。

$dataurl = array('http://test.com/embed-990.html', 
       'http://test2.com/embed-011.html', 
       'http://test3.com/embed-022.html'); 
foreach($dataurl as $url) { 
    switch(parse_url($url, PHP_URL_HOST)) { 
     case 'test.com': 
      echo 'test domain'; 
     break; 
     case 'test2.com': 
      echo 'test domain 2'; 
     break; 
     default: 
      echo 'unknown'; 
     break; 
    } 
    echo $url . PHP_EOL; 
} 

演示:https://3v4l.org/nmukK

Something like SQL 「LIKE」,你可以在preg_match使用正則表達式的問題。

0

您可以使用substr_count

if (substr_count($data['url'], 'test.com') > 0) { 
    echo "my embed code number 1"; 
} 
else if (substr_count($data['url'], 'test2.com') > 0) { 
    echo "my embed code number 2"; 
} 

strpos

if (strpos($data['url'],'test.com') !== false) { 
    echo "my embed code number 1"; 
} 
else if (strpos($data['url'],'test2.com') !== false) { 
    echo "my embed code number 2"; 
} 

preg_match

if(preg_match('/test.com/',$data['url'])) 
{ 
    echo "my embed code number 1"; 
} 
else if(preg_match('/test2.com/',$data['url'])) 
{ 
    echo "my embed code number 2"; 
} 
+0

我不明白完全匹配的目的(你可以用較少的開銷執行'=='),並且你的語法是錯誤的,因爲你需要在Regx中轉義'.',否則它會匹配任何字符例如'/ test2.com /'與'test2-com /'相匹配,請參閱:https://regex101.com/r/snuqRc/2 – ArtisticPhoenix

+0

是的,你是對的,但我試圖建議可能的功能作爲這一點使用。 –

+0

和正則表達式中的確切匹配應該只使用test1或test2,但我認爲這不是一個真正的文本在那裏檢查。 –

0

您可以使用至REGx

$domains = ['test.com', 'test1.com', 'test20.com']; 
foreach($domains as $domain){ 
    if(preg_match('/test([0-9]*)\.com/', $domain, $match)){ 
     echo "my embed code number {$match[1]}\n"; 
    } 
} 

輸出:

my embed code number 
my embed code number 1 
my embed code number 20 

您可以在這裏

http://sandbox.onlinephpfunctions.com/code/1d4ed1d7505a43b5a06b5ef6ef83468b20b47799

測試對於至REGx

  • test比賽test字面上
  • ([0-9]*) - 捕獲組,匹配0-9沒有或多次
  • \.比賽.字面上
  • com比賽com字面上

有一點要注意的是,放置*捕獲組([0-9])*外將匹配並通過如果但不會捕獲捕獲組內的任何內容。這是有道理的,但其重要的要注意,因爲你會得到這樣的信息:

注意:未定義抵消:1 [...] [...]

test.com

如果你想匹配embed-數可以使用根據要如何具體到是這些

 '/test\.com\/embed-([0-9]{3})\.html/' 
    '/\/embed-([0-9]{3})\.html/' 
    '/\/embed-([0-9]{3})\./' 

之一。你可以在這個頁面上玩不同的Regx。

https://regex101.com/r/snuqRc/1

正則表達式是非常強大的,他們是爲了進行模式匹配,這是你所需要的。

乾杯。