Helena
Helena

Reputation: 115

PHP - regular expression (preg_match)

<?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;  
}
?>

I want to preg match the third link and get "D3".
I dont want that it matches with the other two links. This is why it should check if the link has a whitespace at the beginning or the end.
I know that to match with whitespace the expression is \s. I tried but somehow I don't get it. :(

Upvotes: 0

Views: 174

Answers (1)

Chris Mohr
Chris Mohr

Reputation: 3929

You can add the $ to match the end of the string like this, and it will only return the last one.

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

Upvotes: 2

Related Questions