Reputation: 87
I want to check for occurence of a particular string in user input data. How do I do it. Here's my code:
<?php
$data = $_POST["data"];
if (strcmp("123",$data))
echo "string matches";
else if (strcmp("234",$data))
echo "string 2 matches";
else
echo"string does not match";
?>
Upvotes: 2
Views: 43
Reputation: 458
Try this,
<?php
//$data = isset($_POST["data"])?$_POST["data"]:'';
$data = "12356789";
if (strpos($data, "123")!== false){
echo "string matches";
}
else if (strpos($data, "234")!== false){
echo "string 2 matches";
} else {
echo"string does not match";
}
?>
Upvotes: 1
Reputation: 24699
If you want to check to see if $_POST['data']
contains the strings you're searching for, do this:
<?php
$data = $_POST["data"];
if (strpos($data, "123") !== false)
echo "data contains 123";
else if (strpos($data, "234") !== false)
echo "data contains 234";
else
echo "data does not contain either";
But, if you want to check for an exact match, you'd just do:
<?php
//...
if ($data == "123")
echo "data is equal 123";
Check out the manual for strpos()
for more information. For a case-insensitive search, you can use stripos()
(i
for "insensitive") instead.
Checking for strict equality with false
is important. If the match begins at the first character in the string, it will return 0
, which indicates a match. You need !==
to distinguish 0
from false
.
Upvotes: 2
Reputation: 3407
Try this one:
<?php
$data = $_POST["data"];
if (strcmp("123",$data) === 0)
echo "string matches";
else if (strcmp("234",$data))
echo "string 2 matches";
else
echo"string does not match";
?>
Upvotes: 0