substr 函数在 php 中返回错误结果

substr function returning wrong result in php

我是一名 VB.NET 开发人员,从事 PHP 项目,我正在尝试将我的 VB.NET 函数转换为 php,但没有得到想要的结果。调试后发现substr函数有问题

在VB.NET我正在使用

mid(105,2,1) 
This giving me output 0

但在php

substr(105,2,1)
Giving me output 5

如果您想在 PHP 中获取 0,您的代码应该是:

echo substr(105,1,1);

输出:

0

If you want know why, read this:

mid VB.NET

中的函数
Public Shared Function Mid( _
   ByVal str As String, _
   ByVal Start As Integer, _
   Optional ByVal Length As Integer _
) As String

str - Required. String expression from which characters are returned.

Start - Required. Integer expression. Starting position of the characters to return. If Start is greater than the number of characters in str, the Mid function returns a zero-length string (""). Start is one based.

Length Optional. Integer expression. Number of characters to return. If omitted or if there are fewer than Length characters in the text (including the character at position Start), all characters from the start position to the end of the string are returned.

例子

' Creates text string. 
Dim TestString As String = "Mid Function Demo" 
' Returns "Mid". 
Dim FirstWord As String = Mid(TestString, 1, 3)
' Returns "Demo". 
Dim LastWord As String = Mid(TestString, 14, 4)
' Returns "Function Demo". 
Dim MidWords As String = Mid(TestString, 5)

substr函数在PHP

string substr ( string $string , int $start [, int $length ] )

string - The input string. Must be one character or longer.

start - If start is non-negative, the returned string will start at the start'th position in string, counting from zero. For instance, in the string 'abcdef', the character at position 0 is 'a', the character at position 2 is 'c', and so forth.

If start is negative, the returned string will start at the start'th character from the end of string.

If string is less than or equal to start characters long, FALSE will be returned.

例子

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

阅读更多内容:

https://msdn.microsoft.com/en-us/library/05e63829%28v=vs.90%29.aspx

http://php.net/manual/en/function.substr.php

substr() 接受 2 个参数和一个可选的第三个参数

( string, start position, *result length )

*注:结果长度

  • if +ve then 从返回结果的 start 偏移,
  • if -ve then 从返回结果的 end 偏移

示例:

   substr("abcde",2,1);

   // string: "abcde"
   // start position: 2  => returns "cde"
   // result length: 1  => returns "c"


   substr(105,2,1);

   // string: "105"
   // start position: 2  => returns "5"
   // result length: 1  => returns "5"

你可以test substr online here。希望这有帮助。