I have multiple random strings, and I'm trying to pull "SpottedBlanket"
out of the string. Some of them work fine:
DarkBaySpottedBlanket --
DarkBay
BaySpottedBlanket --
Bay
but others are cutting out more than it should.
RedRoanSpottedBlanket --
RedR
BlackSpottedBlanket --
Blac
DunSpottedBlanket --
Du
this is the code I'm using, but I thought it would be self explanatory:
$AppyShortcut = chop($AppyColor,"SpottedBlanket");
$AppyColor
would obviously be the random generated string. Any clue why this is happening?
The chop
function takes the string in the second argument - which in this case is "SpottedBlanket"
, and removes any contiguous characters that it finds from the right hand side.
So for the case of "RedRoanSpottedBlanket"
, you'd get back "RedR"
because "o"
, "a"
, and "n"
are letters that can be found in the string "SpottedBlanket"
.
chop()
is usually used to remove trailing white space - a way of cleaning user input before performing some action on it.
Give your array:
$strings = ["DarkBaySpottedBlanket", "RedRoanSpottedBlanket", "BlackSpottedBlanket", "DunSpottedBlanket"];
What you might be looking for is somerthing like this:
foreach ($strings as $string) {
print substr($string, 0, strrpos($string, "SpottedBlanket")) . "\n";
}
This finds the position of the string from the end using strrpos()
, then returns the start of the string until that position, using substr()
.