Reputation: 303
I have an array that contains more than 100 keys changing dynamically.
([chap1e1], [chap1m1], [chap1h1], ..., [chap100e1], [chap100m1], [chap100h1], ...)
I used the following to remove string from left & right to obtain the dynamic number changing (i.e. 1 - 100 - ...). But here, at the right I need to remove is the last 2 characters exactly.
foreach ($_POST as $k => $v) {
$unit = substr(substr($k, 4), 1, -2);
echo $unit;
}
But the logic seems to be working until, the number is (one digit).
Is there any alternative way of doing this dynamic trim of string from both left & right? Please suggest any idea. Thank You!
SOLUTION using substr()
$unit = substr(substr($k, 4), 0, -2)
Upvotes: 1
Views: 82
Reputation: 164901
You can try a regular expression match, eg
if (preg_match('/^[A-Za-z]{4}(\d+)/', $k, $matches)) {
echo $matches[1];
}
This assumes that the alpha string on the left is only ever 4 characters (ie {4}
in the pattern)
Upvotes: 2