We all know in Visual Basic or VBScript (including VBA i.e. Visual Basic for Application, the Microsoft Office Macro Programming Language), we can easily get the first few (leading) or last few (trailing) characters using left and right respectively. For example,
1 2 3 4 | Dim s s = "Hello, World!" Msgbox Left(s, 3) ' Hel Msgbox Right(s, 3) 'ld! |
Dim s s = "Hello, World!" Msgbox Left(s, 3) ' Hel Msgbox Right(s, 3) 'ld!
In PHP, there is no such functions defined. But we have substr which returns the portion of string given start index and optional length.
string substr ( string $string , int $start [, int $length ] )
So, we can wrap this up,
1 2 3 4 5 6 7 | function left($str, $length) { return substr($str, 0, $length); } function right($str, $length) { return substr($str, -$length); } |
function left($str, $length) { return substr($str, 0, $length); } function right($str, $length) { return substr($str, -$length); }
The start index is from 0, i.e. the first character is at index zero. The start can be negative, which will count the position from the end of the string towards the begining of the string. If the length parameter is omitted, then the substring starts from the start position to the end of the string will be returned. If the length is given and it is positive, then at most length characters beginning with start will be returned.
–EOF (The Ultimate Computing & Technology Blog) —
a WordPress rating system
Last Post: Add a Next Random Post in WordPress Page Template
Next Post: Showing Uptime of Server Status on Webpages using PHP and Crontab