Would anyone have a code to do the following? Say my string is a URL: domain.com/oranges/bananas/ccccKVj1w3q/test.jpg How would I use regex to grab anything starting with /cccc So the regex would output this: ccccKVj1w3q
try this one $str = 'domain.com/oranges/bananas/ccccKVj1w3q/test.jpg'; preg_match('|/(cccc.*?)/|',$str,$match); print_r($match); PHP:
Depending on what you're trying to do, you can do this completely without a regex, and also regardless of the (seemingly) random output before the basename (filename). $url = array_reverse(explode('/',pathinfo('domain.com/oranges/bananas/ccccKVj1w3q/test.jpg')['dirname'])); echo $url[0]; PHP:
I don't understand how that script is going to pinpoint the section of the slashes with the cccc. But I tried it anyways and it seemed to give an unexpected [ on line two where it says ['dirname']. I tried this and it works perfectly for what I need. Thanks again!
My example uses pathinfo (a built-in PHP-function, but it depends on which version of PHP you're running) to return information about the path given - dirname is one of the return-items in the array, and gives 'domain.com/oranges/bananas/ccccKVj1w3q' in the example above. It then takes that string, and using '/' to explode it, creates an array of each item - since you want the last item in the array, we use array_reverse, and pick out [0] - the first item in the new array. It works just fine, since I tested it before posting. pathinfo should run fine on PHP-version above 4.0.3, so... if it's not working, I would take a look at which PHP-version you're running
The parse error comes likely from ...j1w3q/test.jpg')['dirname']. Array dereferencing was added in PHP 5.5. You could fix this by suppling PATHINFO_DIRNAME to pathinfo(). (Untested) $url = array_reverse(explode('/',pathinfo('domain.com/oranges/bananas/ccccKVj1w3q/test.jpg', PATHINFO_DIRNAME))); PHP:
Ah yes, you're right. Function array dereferencing was added in 5.4. 5.5 adds string dereferencing, eg: echo 'this is a string'[3]; PHP: