...

View Full Version : Get first letter from string..



doggo18
05-17-2004, 10:08 PM
How do I get the first letter of a string? I can't seem to figure it out...

for example: '23V6', I want to get the 'V'

Thanks for reading :)

l3vi
05-17-2004, 10:19 PM
I was having the same problem yesterday. Heres how:

First, define the function you will use:


function str_split($string) {
for ($x = 0; $x < strlen($string); $x++) {
$array[$x] = substr($string, $x, 1);
}
return $array;
}

Then, do the code to get the string:


$text = "23V6";
$string = str_split($text, 1);
$string = $string[3];

echo $string;


That should do it. The number in the brackets is the number of the letter you want from the string...

doggo18
05-17-2004, 10:20 PM
Fast response :D Thanks!

:rolleyes: And now why didn't I think of that.. :)

raf
05-18-2004, 12:07 AM
I don't get it.

First off, i don't understand that function at all. It's completely unnescecary, because

$text='23V45';
$string=$text{3};

would give me exacly the same, without needing the function to first turn the string into an array of 1 character elements.

Then i don't understand how all this gets you the first letter.
I mean you here hardcode the position.
In fact, it is wrong, because $string[3] will return '6' because it's a zero based array.

I thought you wanted to dynamically get the first letter from any string, or is it always the third character?

Anyway, the dynamic version would be something like:


$text = "23V6";
for ($i = 0; $i < strlen($text); $i++) {
if (eregi("[a-z]", $text{$i})) {
$string = $text{$i};
break();
}
}

doggo18
05-18-2004, 12:29 AM
Well I did want to do it dynamically.. but his answer gave me the insight to make the loop myself... I didn't want to bother you lot with it anymore since I could figure it out with the part I got from levi.. but I will ofcourse update it with the better solution you posted raf.. it's way more elegant than mine hehe :D

l3vi
05-18-2004, 05:07 AM
Oops, forgot to post that that was for older versions of php that dont support the str_split command :rolleyes:

mordred
05-18-2004, 04:24 PM
You don't necessarily need to define a new function for this problem:



preg_match('/^[^a-z]*([a-z])/im', $string, $matches);


Using the code above, the first letter in a string will appear in $matches[1].

firepages
05-18-2004, 05:09 PM
and for no other reason whatsoever other than to be contrary :D ...



<?
echo substr( $text,( strspn( $text , "1234567890" ) +1 ) ,1 ) ;
?>


ok ok I admit it , it's cos I can't do regex ;)



EZ Archive Ads Plugin for vBulletin Copyright 2006 Computer Help Forum