tags:

views:

99

answers:

6

Here is the suject:

http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov

What I need using regex is only the bit before the last / (including that last / too) Now this 937IPiztQG bit can change, it has a-z A-Z 0-9 - _

Heres the code i wrote but it doesnt work

$code = strstr($url, '/http:\/\/www\.mysite\.com\/files\/get\/([A-Za-z0-9]+)./');



EDIT: The reason i need to use regex is because I dont actually know the url I have string like this...

<a href="http://www.mysite.com/files/get/1B-MenlPW0/my-file.doc"&gt;a song</a>
<a href="http://www.mysite.com/files/get/1ZeR5KEo9x/my-song.mp3"&gt;more text</a>
<a href="http://www.mysite.com/files/get/8IySvO5gMD/my-video.avi"&gt;oh and here goes some more blah blah</a>

I need it to read that string and cut off filename bit of the url's

A: 
/http:\/\/www.mysite.com\/files\/get\/([^/]+)\/

How about something like this? Which should capture anything that's not a /, 1 or more times before a /.

meder
A: 

The strstr() function does not use a regular expression for any of its arguments it's the wrong function for regex replacement.

Are you thinking of preg_replace()?

But a function like basename() would be more appropriate.

pavium
Im not looking to replace it with anything, I need to get that url using $code
Imran
Ok, but my point was that strstr doesn't understand regexes, preg_replace (or preg_match) *do* but simply extracting the filename or folder name is a job for another function. Perhaps I should have suggested dirname()
pavium
A: 

The greediness of regexp will assure this works fine ^.*/

Petr Topol
+1  A: 

This seems far too simple to use regex. Use something similar to strrpos to look for the last occurrence of the '/' character, and then use substr to trim the string.

beta
+4  A: 

You really don't need a regexp here. Here is a simple solution:

echo basename(dirname('http://www.mysite.com/files/get/937IPiztQG/the-blah-blah-text-i-dont-need.mov'));
// echoes "937IPiztQG"

Also, I'd like to quote Jamie Zawinski:

"Some people, when confronted with a problem, think 'I know, I'll use regular expressions.' Now they have two problems."

naixn
+1 for a good answer, -1 for the over(ab)used JZ quote. I'm just so sick of hearing that quote.
Chris Lutz
A: 

Try this

$ok=preg_match('#mysite\.com/files/get/([^/]*)#i',$url,$m);
if($ok) $code=$m[1];

Then give a good read to these pages

Note

  • the use of "#" as a delimiter to avoid getting trapped into escaping too many "/"
  • the "i" flag making match insensitive (allowing more liberal spellings of the MySite.com domain name)
  • the $m array of captured results
ZJR
This only get finds matches on links how i desire them to be.I need a script that actually changes those links inside the string to how i desire
Imran
hence something like$url=preg_replace('#http://www\.mysite\.com/files/get/([^/]*)[^"]*#i','smtg \1 smtg',$url);
ZJR