Detecting a plus or minus at the end of a string

For some reason my logic is not working. I’m trying to detect if the last character of a string is a + or a - Can someone see what I’m overlooking?


// They typed a plus or minus at the end of their search
$LastCharacter = substr("$q", -1); 
if ($lastCharacter == "+" || $lastCharacter == "-") { 
  $formError = "Yes";
  $errorMessage .= "<li>You typed a plus or minus at the end of your search, $q.  The plus and minus signs must be at the beginning of each search word.</li>";


Never mind, I got this figured out.


Ok, I thought I got it figured out but I didn’t. The following code, slightly changed from my first example, works on strings like +lavender lemon- but not +lavender lemon+

Any ideas?


if (preg_match("/+\z/", $q) || preg_match("/-\z/", $q)) {

I forgot to escape the + sign. Once I did the code is working as desired.


1 Like

I haven’t fully tested this, but I think you can do this in a single expression (if that is of any interest to you).

if (preg_match("/(\+|-)\z/", $q)) {

Thank you, I updated my code and it works great!

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.