determining the last character of a string?
Moderator: General Moderators
-
psychomachine
- Forum Newbie
- Posts: 17
- Joined: Wed Mar 03, 2004 1:18 pm
determining the last character of a string?
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
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
a example if u want:
this will return the last letter, "s" in this case.
Code: Select all
<?php
$exam = substr("evilwalrus", -1);
?>-
psychomachine
- Forum Newbie
- Posts: 17
- Joined: Wed Mar 03, 2004 1:18 pm
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.
many thanks, again.
-
psychomachine
- Forum Newbie
- Posts: 17
- Joined: Wed Mar 03, 2004 1:18 pm
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.
Code: Select all
$string="Hello"l
echo $string[4];Code: Select all
echo $string[strlen($string)-2];Edit: ack, too tired. Just read your message regarding unicode - the code above can be modified for that purpose.
-
psychomachine
- Forum Newbie
- Posts: 17
- Joined: Wed Mar 03, 2004 1:18 pm
tim said:
$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
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.would you mind posting the code so I can see it? curious =]
$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