PHP - 正则表达式(preg_match)

时间:2012-06-10 15:31:56

标签: php regex preg-match preg-match-all

<?php
$string = "http://example.com/file/D1 http://example.com/file/D2
http://example.com/file/D3";
preg_match_all('/(https?\:\/\/)?(www\.)?example\.com\/file\/(\w+)/i', $string, $matches);  
foreach($matches[3] as $value)
{  
print $value;  
}
?>

我想要匹配第三个链接并获得“D3”。
我不希望它与其他两个链接匹配。这就是它应该检查链接在开头或结尾是否有空格的原因 我知道要与空格匹配,表达式为\s。我尝试但不知怎的,我没有得到它。 :(

1 个答案:

答案 0 :(得分:2)

你可以像这样添加$以匹配字符串的结尾,它只会返回最后一个字符串。

preg_match_all('/(https?\:\/\/)?(www\.)?example\.com\/file\/(\w+)$/i', $string, $matches);  
相关问题