2012-07-10 54 views
0

我在下面的php例子中有一個字符串。PHP查找字符串中的鏈接

$string = "This is my website example.org check it out!"; 
if(preg_match('/\w+\.(?:com|org)/i', $string, $matches)) { 
var_dump($matches[0]); 
echo '' . $matches[0] . ''; 
} 

將回聲出

string(11) "example.org" example.org 

我需要它只能隨聲附和了只有

example.org

+0

帶出var_dump – Ben 2012-07-10 01:15:37

+0

謝謝@Ben! – 2012-07-10 01:19:52

+0

你不應該重寫整個問題來詢問別的東西。只需添加「更新」文本。至於你的問題,請參閱關於'var_dump'的手冊:http://www.php.net/manual/en/function.var-dump.php – Timur 2012-07-10 01:33:59

回答

0

你需要一個正則表達式來做到這一點。這裏是一個開始:

$string = "This is my website example.org check it out!"; 
if(preg_match('/\w+\.(?:com|org)/i', $string, $matches)) { 
    // var_dump($matches[0]); 
    // echo '<a href="' . $matches[0] . '">' . $matches[0] . '</a>'; 
    echo $matches[0]; 
} 

的正則表達式是:

\w+\.(?:com|org) 
^ ^^ 
| |Match either com or org 
| Match a period 
Match one or more word character [A-Za-z0-9_] 

will output

string(11) "example.org" 

你需要去適應它,包括子域和協議,如果需要的話。

+0

它工作的很好,除了我如何得到它只是回聲域只輸出,而不是字符串(11)「」。子域名會很好,你會怎麼做?謝謝! – 2012-07-10 00:48:05