从字符串 PHP 中删除前 3 个字符和后 3 个字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7045618/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 01:52:46  来源:igfitidea点击:

Delete first 3 characters and last 3 characters from String PHP

phpstringcharacterstripsubstr

提问by Howdy_McGee

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 first and last characters i'm not sure if I can actually use this. Any suggestions?

我需要删除字符串的前 3 个字母和字符串的后 3 个字母。我知道我可以使用 substr() 从某个字符开始,但是如果我需要去掉第一个和最后一个字符,我不确定我是否真的可以使用它。有什么建议?

回答by Sean Bright

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

将负值作为length参数(第三个参数)传递给substr(),例如:

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

So this:

所以这:

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

Outputs:

输出:

n Bri

回答by James

Use

substr($var,1,-1)

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

这将始终是第一个和最后一个,而不必使用 strlen。

Example:

例子:

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

Output:

输出:

a,b,d,e,f

a,b,d,e,f

回答by mgutt

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

如其他答案所述,您可以使用以下功能之一来实现您的目标:

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.

这取决于您需要删除的字符数量以及删除是否需要具体。但最终substr()完美地回答了你的问题。

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

也许有人考虑通过string dereferencing删除第一个/最后一个字符。忘记这一点,它也不会像null字符那样工作:

<?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:

并且不能unset($string[0])用于字符串:

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

致命错误:无法在/usr/www/***.php线上取消设置字符串偏移量**

回答by Maxim Krizhanovsky

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

回答by Antony Scott

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?

我不知道 php,但你不能取字符串的长度,从位置 3 开始并使用 substr 取长度为 6 个字符吗?

回答by Jonathan M

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