substr 函数如何工作? [英] How substr function works?

查看:28
本文介绍了substr 函数如何工作?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在 php.net 中遇到过这段代码.

I have come across this code in php.net.

<?php
echo substr('abcdef', 1);     // bcdef
echo substr('abcdef', 1, 3);  // bcd
echo substr('abcdef', 0, 4);  // abcd
echo substr('abcdef', 0, 8);  // abcdef
echo substr('abcdef', -1, 1); // f

// Accessing single characters in a string
// can also be achieved using "square brackets"
$string = 'abcdef';
echo $string[0];                 // a
echo $string[3];                 // d
echo $string[strlen($string)-1]; // f

?>

substr('abcdef',1,3) 返回 'bcd',最后一个索引是 3,它返回 "bcd"如果我执行 substr('abcdef',0,4) 返回 'abcd'.但与第一个示例相比,我希望 substr('abcdef',0,3) 返回 'abcd' .我在这里错过了什么.

substr('abcdef',1,3) returns 'bcd', the last index is 3 and it returns "bcd" and if I do substr('abcdef',0,4) returns 'abcd'. But I expected substr('abcdef',0,3) to return 'abcd' as compared to the first example. What am I missing here.

substr($string,$start,$last) 在 php 中是如何工作的?

How substr($string,$start,$last) works in php?

对不起,我认为第三个参数不是长度和超出我理解的东西......由于我的 Java 背景抱歉.感谢所有评论和回答.

Sorry every body I thought 3rd param is not length and something beyond my understanding...due to my Java background sorry. Thanks for all comments and answers.

推荐答案

substr() is NOT substr($string, $start, $last) 它是 substr($string, $start, $length).所以 substr('abcdef', 0, 4) 返回 abcd 因为它从 0 (a) 开始,它有 4 个字母.

substr() is NOT substr($string, $start, $last) it's substr($string, $start, $length). So substr('abcdef', 0, 4) returns abcd because it starts at 0 (a) and it goes for 4 letters.

还有随机注释:echo substr('abcdef', -1, 1); 本质上是多余的,因为 -1 的长度只有 1,所以字符串也可能是:echo substr('abcdef', -1);

Also random note: echo substr('abcdef', -1, 1); is inherently redundant since -1 only has a length of 1 so the string might as well be: echo substr('abcdef', -1);

这篇关于substr 函数如何工作?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆