potato
potato

Reputation: 4589

intermediate string processing with php

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?

Upvotes: 0

Views: 35

Answers (1)

Jay Blanchard
Jay Blanchard

Reputation: 34416

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.

Upvotes: 3

Related Questions