|
Posted by Mladen Gogala on 10/23/49 11:40
On Mon, 20 Feb 2006 01:22:48 +0000, Jim Carlock wrote:
> Does PHP provide a function to extract the rightmost characters from a
> string?
>
> For example, the VB/ASP equivalent...
>
> sStateAbbr = Right$(sCityState, 2)
You should pay more detailed attention to the manual. Standard PHP
"substr" function does that, without any additional functions. Here is
what the fine manual says:
Description
string substr ( string string, int start [, int length] )
substr() returns the portion of string specified by the start and length
parameters.
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.
Example 1. Basic substr() usage
<?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 achived using
"curly braces" $string = 'abcdef';
echo $string{0}; // a
echo $string{3}; // d
echo $string{strlen($string)-1}; // f
?>
If start is negative, the returned string will start at the start'th
character from the end of string.
Here is an example:
#!/usr/local/bin/php
<?php
$a="Usenet is a great tool";
echo substr($a,-4),"\n";
?>
When executed, the output given is "tool".
--
http://www.mgogala.com
[Back to original message]
|