Home » Php » PHP Match a string exactly

PHP Match a string exactly

Posted by: admin July 12, 2020 Leave a comment

Questions:
$check = 'this is a string 111';
if ($check = 'this is a string') {
echo 'perfect match';
} else {
echo 'it did not match up';
}

But it returns perfect match everytime instead of it did not match up… I can not seem to get the string to match the case exactly it will only work if part of the string matches up.

If i try to complicate things a little using board code and regex patterns it becomes a nightmare.

if ($check = '/\[quote(.*?)\](.*?)\[\/quote\]/su') {
$spam['spam'] = true;
$spam['error'] .= 'Spam post quote.<br />';
}

So if the post only contained quote tags it would be considered spam and ditched but i can not seem to solve it perhaps my patterns are wrong.

How to&Answers:

You need to use == not just =

$check = 'this is a string 111';
if ($check == 'this is a string') {
echo 'perfect match';
} else {
echo 'it did not match up';
}

= will assign the variable.

== will do a loose comparison

=== will do a strict comparison

See comparison operators for more information.

Answer:

For equality comparison you want the == operator. = is assignment.

if ($check = 'this is a string') {

should be

if ($check == 'this is a string') {

Don’t worry, we’ve all done it. I still do 🙂

Answer:

You’re using the assignment operator, =, instead of the equality operator ==.

You need to use

if ($check == 'this is a string') {

Answer:

if ($check = 'this is a string') assigns the string to $check variable which is always defined and thus, returns always true in the if

should be if ($check == 'this is a string')

Answer:

the == comparison operator will work in most cases, but fails to do an exact match in some edge cases*.

Using === operator is best.

if ($check === 'this is a string') {

An example where == works unexpectedly

$check = '2';
if ($check == '          2') {