Jack Maessen Jack Maessen - 6 months ago 13
PHP Question

how to grab part of a url string with php

I am using a filemangement system and to protect the url. Manipulation of the url string is not allowed and leads to killing the page.
I want to make an exception for that when I delete files.

When deleting files, the url string always looks like this:

example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b/folder1


or

example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b/file.jpg


or

example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b/folder1/file.jpg


So the minimum of the string contains always:

example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b


( the hash is a md5 hash of a userid)

So how can I grab that minimum url string?

Answer

Use implode, array_slice, explode.

Explode will extract the string to array, array slice cut the array upto 4th item, and implode will grab the array items to a new string.

$str = 'example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b/folder1 ';

echo $output = implode('/', array_slice(explode("/", $str), 0, 4)); //example.com/sfm?delete=uploads/sfm/c4ca4238a0b923820dcc509a6f75849b
Comments