[SOLVED] Remove first and last word from a string(php))

Issue

I want to remove the first and last word from a string.

$string = "12121";

I tried trimming it like

$string = "12121";
$trimmed = trim($string, 1);
print($trimmed);

Result
22
And I want
212
So please help me

Solution

You can try Regular expressions

$string = "12121";
$trimmed = preg_replace('(^.)', '', $string);
$trimmed = preg_replace('(.$)', '', $trimmed);
print($trimmed);

but it seems overkill to use regex in this
so substr(like @aqib mentioned) might be the one you’re looking for

$string = "12121";
$trimmed = substr($string, 1, -1);
print($trimmed);

Answered By – tenshi

Answer Checked By – Senaida (BugsFixing Volunteer)

Leave a Reply

Your email address will not be published. Required fields are marked *