开发者

Delete first 3 characters and last 3 characters from String PHP

开发者 https://www.devze.com 2023-03-27 15:01 出处:网络
I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both fi开发者_如何学运维rst and la

I need to delete the first 3 letters of a string and the last 3 letters of a string. I know I can use substr() to start at a certain character but if I need to strip both fi开发者_如何学运维rst and last characters i'm not sure if I can actually use this. Any suggestions?


Pass a negative value as the length argument (the 3rd argument) to substr(), like:

$result = substr($string, 3, -3);

So this:

<?php
$string = "Sean Bright";
$string = substr($string, 3, -3);
echo $string;
?>

Outputs:

n Bri


Use

substr($var,1,-1)

this will always get first and last without having to use strlen.

Example:

<?php
    $input = ",a,b,d,e,f,";
    $output = substr($input, 1, -1);
    echo $output;
?>

Output:

a,b,d,e,f


As stated in other answers you can use one of the following functions to reach your goal:

  • substr($string, 3, -3) removes 3 chars from start and end
  • trim($string, ",") removes all specific chars from start and end
  • ltrim($string, ".") removes all specific chars from start
  • rtrim($string, ";") removes all specific chars from end

It depends on the amount of chars you need to remove and if the removal needs to be specific. But finally substr() answers your question perfectly.

Maybe someone thinks about removing the first/last char through string dereferencing. Forget that, it will not work as null is a char as well:

<?php
$string = 'Stackoverflow';
var_dump($string);
$string[0] = null;
var_dump($string);
$string[0] = null;
var_dump($string);
echo ord($string[0]) . PHP_EOL;
$string[1] = '';
var_dump($string);
echo ord($string[1]) . PHP_EOL;
?>

returns:

string(13) "Stackoverflow"
string(13) "tackoverflow"
string(13) "tackoverflow"
0
string(13) "ackoverflow"
0

And it is not possible to use unset($string[0]) for strings:

Fatal error: Cannot unset string offsets in /usr/www/***.php on line **


substr($string, 3, strlen($string) - 6)


I don't know php, but can't you take the length of the string, start as position 3 and take length-6 characters using substr?


$myString='123456789';
$newString=substr($myString,3,-3);
0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号