totallyuneekname
totallyuneekname

Reputation: 2020

Take question mark off end of string in PHP

I'm new to php, but wasn't able to find a straight answer online, so decided to ask Stack Overflow.

I have a variable, and I want to make a statement similar to the following:

if ($var has a question mark at end)
{
$var = ($var - question mark)
}

Thanks in advance!

--EDIT--

I ended up using the following:

if (substr($var, -1) == "?")
{
$var = rtrim($input, "?");
}

Thanks again for the quick feedback. God I love this site.

--END EDIT--

Upvotes: 1

Views: 1186

Answers (5)

Fabio
Fabio

Reputation: 23500

What about using strpos function?

example

$mystring = 'abc?';
$findme   = '?';
$pos = strpos($mystring, $findme);

if($pos === true)
{
      //we've found it
}

Upvotes: 0

ILikeTacos
ILikeTacos

Reputation: 18676

$var = (substr($var,-1) == "?") ? substr($var,0,-1) : $var;

Explanation:

substr($var, -1) gets the last character in your string

then it compares whether that string has question mark or not at the end.

If it has a question mark at the end, it removes it, if it doesn't it leaves the string as is.

The code above is a shorthand version of if(){....} else {} The instructions after the unquoted question mark represent the true block, the instructions after the colon : represent the false block.

Upvotes: 0

Disenchanted
Disenchanted

Reputation: 613

hakre is right

$var = rtrim($var, '?');

Upvotes: 2

Corné Guijt
Corné Guijt

Reputation: 122

Simple answer:

$var = rtrim($var, '?');

Upvotes: 1

joshuahealy
joshuahealy

Reputation: 3569

Just do this:

if ($var[strlen($var) - 1] == "?")
{
    $var = substr($var, 0, strlen($var) - 1);
}

Upvotes: 0

Related Questions