JSking
JSking

Reputation: 419

Isolate substring after the first n characters and before the last n characters

Using the substr() how do I remove the first and last 3 characters in a string and return the middle remaining characters? eg:

$a = 'abc34828xyz';
$a = 'abc347283828xyz';
$a = 'abc347w83828xyz';
// return first 3
return $first = substr($a, 0, 3);
// return last 3
return $last = substr($a, -3);
// return the string in middle
// $mid = ? now how do we always get the ones in the middle

Upvotes: 0

Views: 6794

Answers (4)

mickmackusa
mickmackusa

Reputation: 47883

Simply use substr() with a starting offset of 3 and a negative limit parameter to indicate how many offsets to subtract from the end of the string.

Code: (Demo)

$string = 'abc347w83828xyz';
echo substr($string, 3, -3);  '347w83828'

For clarity, if your input string is abcde, then the returned value will be an empty string.

Upvotes: 0

Goaul
Goaul

Reputation: 1560

If anyone wants a generic way to just return middle character of a string:

function getMiddle($text): string
{
    $length = round((strlen($text)) / 2);
    if (strlen($text) % 2 === 0)
    {
        //even, returns 2 characters
        return $text[(int) $length - 1] . $text[(int) $length];
    }
    //odd, returns 1 character
    return $text[(int) $length - 1];
}

or

function getMiddle($text): string
{
    $start = floor((strlen($text) - 1) / 2);
    $len = strlen($text) % 2 ? 1 : 2;
    return substr($text, $start, $len);
}

echo getMiddle("middle") . PHP_EOL;
echo getMiddle("testing") . PHP_EOL;
echo getMiddle("A") . PHP_EOL;

output:

dd
t
A

Upvotes: 0

mhall
mhall

Reputation: 3701

You can get it using preg_replace:

$a = 'abc347w83828xyz';
$mid = preg_replace('/...(.*).../', '$1', $a);
echo $mid, PHP_EOL;

Output:

347w83828

And if you want you can actually get them all at once by using a preg_match call:

$a = 'abc347w83828xyz';
preg_match('/(...)(.*)(...)/', $a, $matches);

echo "First: ", $matches[1], PHP_EOL;
echo "Mid:   ", $matches[2], PHP_EOL;
echo "Last:  ", $matches[3], PHP_EOL;

Output:

First: abc
Mid:   347w83828
Last:  xyz

Upvotes: 1

Rizier123
Rizier123

Reputation: 59681

This should work for you:

(Just start with an offset of 3 and then take the length where you subtract 2*3 (6))

echo $middle = substr($a, 3, strlen($a)-6);

Upvotes: 1

Related Questions