Amy Neville
Amy Neville

Reputation: 10621

Check if last character is a question mark

How do I check if the last character in a string is a question mark (?) using php?

This is my current attempt but it doesn't seem to work unfortunately:

if (substr(strrev(trim($link)),0,0) != "?")
{

}

Upvotes: 1

Views: 2667

Answers (4)

suz
suz

Reputation: 747

The easiest way is:

if (substr("question?", -1) == '?')

Sometimes I check also other marks like ? ! or . :

if (in_array(substr("question?", -1), ['?', '!' , '.']))

Upvotes: 0

user557846
user557846

Reputation:

it's php, there are always alternatives:

$link='123?';
if (end(str_split($link)) == "?"){
    echo 'YES';
}

Upvotes: 0

user764357
user764357

Reputation:

There are two main errors with your code. Firstly, the comparision is wrong. You are asking if the last character is not a question mark. Also, you are getting a 0 length substring, so that will always be not equal to a question mark, since '' != '?' is always True.

With your original code you can change it to this:

if (substr(strrev(trim($link)),0,1) == "?")
{
    //Do things
}

Alternatively, this is slightly shorter and just counts the index for the substring from the end:

$link = "Say what?";
if (substr($link,-1) == "?")
{
 echo "You heard me!";
}

Upvotes: 1

Barmar
Barmar

Reputation: 782785

if (substr(rtrim($link), -1) != "?") { 
  // Do stuff
}

Giving a negative start value to substr() makes it count from the end instead of the beginning.

Upvotes: 9

Related Questions