0

This is the string a want to process: "very, very, Random Stringby Random $10" The fixed strings are $ and the last by. I do not know how many by's it will be before the last one.

I am looking for a way to unambiguously cut out the "by Random"("by" and the string/strings between $ sign) out of string.

I though I could do this by accessing the position of $ sign(I know there will always be $ sign in there at the right position) with strpos function and the position of the first "by" before $ sign. But I don't know how to tell it to look for the first "by" before the selected position, namely the $ sign. What approach do you recommend that I take?

3
  • You've provided a lot of words that don't describe what you want: Given your input string, what exactly do you expect / want back from it? Commented Feb 1, 2016 at 21:30
  • try strripos(), it matches from the end of the string, e.g. strripos('by', $str) would find the last by. Commented Feb 1, 2016 at 21:30
  • Thanks Marc B, I will do that! Commented Feb 1, 2016 at 21:33

1 Answer 1

3

If you use strripos() you can get the last portion of the string by combining that function with the substr() function like this:

$string = "very, very,  Random Stringby by by Random $10";
echo substr($string, strripos($string, 'by')); // by Random $10

Note that this PHP function is one of those requiring the haystack first, then the needle.


NOTE: I was bitten by the order of the needle and haystack earlier today on this very function.

Sign up to request clarification or add additional context in comments.

2 Comments

thank you. this seems optimal. Just a quick question before I dive into testing. Since it goes in reverse...will it return the position of "b" or "y" of "by"?
It returns the position of the first character in the needle @krompir2

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.