2

How can I extract specific sub string from a Main String from specific string to specific end String. Like I have below path

your path is D:///path/to/required/directory/sample/subdirectory/a/b/abc/sample.text

from above path I want to extract sub string from /sample to abc. In detail

/sample/subdirectory/a/b/abc

I tried with other substring functions but no success.

Can anybody help me for this?

I had tried with one of example given in php.net site

function reverse_strrchr($haystack, $needle, $trail)
{
        return strrpos($haystack, $needle) ? substr($haystack, 0, strrpos($haystack, $needle) + $trail) : false;
}

but it gives me below path but I want to start from /sample to end

your path is D:///path/to/required/directory/sample/subdirectory/a/b/abc

2
  • Is the path likely to be static at all times or will this function be used to grab files from multiple locations? Commented Sep 26, 2013 at 8:03
  • @ChrisBertrand No. It will be dynamic every time but /sample will always be available in path. Commented Sep 26, 2013 at 8:05

2 Answers 2

2

I think you would like this. It is proper what you need is.

Your Main String is: D:///path/to/required/directory/sample/subdirectory/a/b/abc/sample.text

You want to Start Extract From "/sample" ( First "sample" word )

You want to Stop Extract To "/sample" ( Last "sample" word )

Will return the following string as Answer "/sample/subdirectory/a/b/abc/sample"

$mainstr = "D:///path/to/required/directory/sample/subdirectory/a/b/abc/sample.text";
$needle = "/sample";
$trail  = "/sample";

echo $this->reverse_strrchr($mainstr, $needle, $trail);

Function definition is:

function reverse_strrchr($haystack, $needle, $trail)
{
    $start  = strpos($haystack, $needle);
    $total  = strrpos($haystack, $trail) - strpos($haystack, $needle) + strlen($trail);
    $result = substr($haystack, $start, $total);
    return $result;
}
Sign up to request clarification or add additional context in comments.

Comments

1

You start from position 0.

substr($haystack, 0, strrpos($haystack, $needle) + $trail)

Search the position of /sample and replace it with 0.

For example:

$haystack = -- your path here --;
$result = substr($haystack, strrpos($haystack, "/sample"), strrpos($haystack, "abc"));
echo $result; // Your new "path"

3 Comments

I tried with strpos($str","/sample") but not giving proper position.
Thanks for quick and perfect reply. I have just modified your version. Like $str = (reverse_strrchr($str, "/", 0));$result = substr($str, strrpos($str, "/sample")); and now it's giving me a path what I needed. I appreciate it ;)
Check my answer below will be helpful

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.