Page 1 of 1 [ 3 posts ] 

Albinoboy
Yellow-bellied Woodpecker
Yellow-bellied Woodpecker

User avatar

Joined: 5 Aug 2010
Age: 31
Gender: Male
Posts: 70
Location: Surrey, England

03 Sep 2010, 7:47 pm

Ok so I need PHP to keep all the text before the last delimiter.

For example:
one/two/three
The text that remains:
one/two



one-A-N
Veteran
Veteran

User avatar

Joined: 2 Mar 2010
Age: 72
Gender: Male
Posts: 883
Location: Sydney

03 Sep 2010, 9:16 pm

Depends on what you are trying to do.

If you want to extract the path from a filename .. e.g. from "/home/foo/myfile.txt" you want "/home/foo" then just use the dirname function which was designed for this purpose:

$path = dirname('/home/foo/example.txt');
echo $path;

result is "/home/foo".

Another way that you can use with any delimiter, not just '/': split the string into an array (use explode); then pop the last element (use array_pop); then join the array back with your delimiter (use implode):

$items = explode('/', '/foo/bar/baz/bat');
array_pop($items); // discard last element of array (i.e. 'bat')
$result = implode('/', $items);
// $result is now '/foo/bar/baz'

The nice thing about this method is that you can also convert your delimiter along the way, if you want: e.g. you can turn '\foo\bar\baz\bat' into '/foo/bar/baz'

Another, very simple way:

$foo = '/foo/bar/baz/bat';

$result = substr($foo, 0, strrpos($foo, '/')-1);

That extracts everything before the last '/'. But you need to add code to check that strrpos doesn't return "false". BTW, note that strrpos has two 'r's - it is STRing-Reverse-POSition - not to be confused with strpos, which is STRing-POSition.

Hope that helps

PS you can also do it with regular expressions, but the above methods are easier and simpler to understand



Albinoboy
Yellow-bellied Woodpecker
Yellow-bellied Woodpecker

User avatar

Joined: 5 Aug 2010
Age: 31
Gender: Male
Posts: 70
Location: Surrey, England

03 Sep 2010, 9:52 pm

thx, that did the trick