Home > Software engineering >  Remove first and last word from a string(php))
Remove first and last word from a string(php))

Time:03-03

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

CodePudding user response:

try this

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

CodePudding user response:

can you try this?

<!DOCTYPE html>
<html>
<body>
<?php
$string = "12121";
$temp = ltrim($string, 1);
$trimmed = rtrim($temp, 1);
print($trimmed);
?>

</body>
</html>

CodePudding user response:

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);
  • Related