Page 1 of 1
determining the last character of a string?
Posted: Sun Mar 07, 2004 12:49 pm
by psychomachine
hello there.
i have a mysql query that returns a string and puts it in a variable
$string
I need to check if the last character of $string is "a", "b" or "c"; and if it is, create a new variable
$newstring
which will be the same as $string, except "a" will be replaced by "d", "b" will be replaced by "e", and "c" will be replaced by "f".
many thanks in advance.
psychostuck
Posted: Sun Mar 07, 2004 12:53 pm
by Deemo
substr()
use that, and another idea would be to use strrev, and then read the last letter, which is now the first letter

Posted: Sun Mar 07, 2004 1:00 pm
by tim
a example if u want:
Code: Select all
<?php
$exam = substr("evilwalrus", -1);
?>
this will return the last letter, "s" in this case.
Posted: Sun Mar 07, 2004 2:10 pm
by psychomachine
sorry, i forgot to mention the most important thing!!!! the strings from the database are utf8 encoded cyrillic characters. so each character is actually two bytes, which is why the above suggestions don't work. how does one make sure that the last character is actually the last unicode character?
many thanks, again.
Posted: Wed Mar 10, 2004 4:50 am
by psychomachine
ok, figured it out. the solution is to use mb functions, but if you can't, simply count each character as two. it works.
Posted: Wed Mar 10, 2004 4:55 pm
by tim
would you mind posting the code so I can see it? curious =]
Posted: Wed Mar 10, 2004 5:00 pm
by Weirdan
[php_man]mb_substr[/php_man] I guess

Posted: Wed Mar 10, 2004 5:07 pm
by patrikG
Alternatively you can treat a string as an array. Meaning:
should output "o"
should output the last character of a string. Note: -2 since arrays are indexed starting with 0, while the strlen counter starts with 1.
Edit: ack, too tired. Just read your message regarding unicode - the code above can be modified for that purpose.
Posted: Thu Mar 11, 2004 1:03 am
by psychomachine
tim said:
would you mind posting the code so I can see it? curious =]
sure. without using mbstring, php thinks that each byte is one character. so, in order to get one unicode character, we are telling php to get two character bytes.
$lastletter = substr($string, -2);
and to get the word without the last letter:
$allbutlast= substr($string, 0 (strlen($string)-2));
tested and works with utf8 cyrillic from my db.
all best,
psychomachine