2014-02-18 14 views
-2

我有以下給出的主機名,我想preg_match特定模式。PHP preg_match主機名中的特定模式

主機名:

sub1.hostname1.com 
sub12.hostname2.com 
suboo2.hostname3.com 
sub2.hostname4.com 

所需的輸出的preg_match後:

sub1.hostname1.com 
suboo2.hostname3.com 
sub2.hostname4.com 

的想法是讓有子域中的一個12主機名。

+0

你有試過什麼嗎?如果是的話,把你的代碼 –

+0

不,我沒有掙扎。我得到了一個基於sed的正則表達式匹配,但不適用於php。 – basic1point0

+0

對於數組,請嘗試'preg_grep'。 – AbraCadaver

回答

-1

如果你有一張紙,一支筆,你被要求寫下一個簡單的算法,這樣做,你會怎麼做呢?

這是我會怎麼做:

  1. 您可以確定子域,在字符串中,通過查找第一個點。因此,找到第一個點,然後提取子域。

  2. 由於我們只關心我們可以在邏輯上的數字,刪除任何不是數字的東西。

  3. 現在我們只有一個數字,它應該很簡單,以評估它是否是我們想要的。

在代碼中,你可以做這樣的事情:

$samples = [ 
    'sub1.hostname1.com', 
    'sub12.hostname2.com', 
    'suboo2.hostname3.com', 
    'sub2.hostname4.com', 
]; 
foreach ($samples as $domain) { 

    // Find the sub-domain 
    $dot = strpos($domain, '.'); 
    if ($dot === false) { 
     continue; 
    } 
    $sub = substr($domain, 0, $dot); 

    // Remove non-numbers from the sub-domain 
    $number = filter_var($sub, FILTER_SANITIZE_NUMBER_INT); 

    // Check that it is what we want 
    if ($number == 1 or $number == 2) { 
     echo "$domain is a $number sub-domain<br>"; 
    } 
} 

我會離開它作爲一個練習扔東西到一個函數,如果這是你在找什麼。

如果你絕對要使用正則表達式的話,那就只是檢查數子域名的問題:

foreach ($samples as $domain) { 
    $matches = preg_match('/^[^0-9]+(?:1|2)\./', $domain); 
    if ($matches === 1) { 
     echo "$domain is a 1 or 2 sub-domain<br>"; 
    } 
} 
+0

你是一個搖滾明星!謝啦。 – basic1point0

+0

您的正則表達式不適用於以**開頭的子域。事實上,它只適用於以** 1或2結尾的那些。 – Phil

+0

@我知道。我根據問題中給出的例子回答了我的答案;他們只用數字結尾*。如果提問者想要匹配更復雜的模式,那麼他們需要更徹底地解釋它。 –

0

聽起來更像你想過濾器陣列。試試這個...

$filtered = array_filter($hostnames, function($hostname) { 
    // assume that the "subdomain" is the first hostname segment, separated by "." 
    list($subdomain, $theRest) = explode('.', $hostname, 2); 

    return preg_match_all('/1|2/', $subdomain) === 1; 
}); 

演示在這裏 - http://ideone.com/MwbS7T

0

你的問題是相當不明確,但是從意見我可以提取的含義如下:

匹配的子域,其包含恰好一個「1」或恰好一個「2」,但不能同時

這一要求轉化爲以下代碼:

$subdom = strstr($host, '.', true); 

$matched = substr_count($subdom, '1') == 1^substr_count($subdom, '2') == 1; 

^(XOR)操作者可確保與兩個「1」和「2」的子域不計算在內。