This question already has answers here:
How do I check if a string contains a specific word?
(36 answers)
Closed 1 year ago.
I have 2 strings $verify and $test. I want to check if $test contains elements from $verify at specific points. $test[4] = e and $test[9] = ]. How can I check if e and ] in $verify?
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if ($test[4] == $verify AND $test[9] == $verify) {
echo "Match";
} else {
echo "No Match";
}
Use strpos() https://www.php.net/manual/en/function.strpos.php
https://paiza.io/projects/n10TMV4Ate8-vtzioDrsMg
<?php
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if (strpos($verify, $test[4]) !== false && strpos($verify, $test[9]) !== false) {
echo "Match";
} else {
echo "No Match";
}
?>
As of PHP8 you can use str_contains()
<?php
$verify = "aes7]";
$test = "09ske-2?;]3fs{";
if (str_contains($verify, $test[4]) && str_contains($verify, $test[9])) {
echo "Match";
} else {
echo "No Match";
}
?>
Thanks to #symlink for the code snippet I butchered
Related
In my php I have 2 optional inputs. input1= and input2=. Both are optional inputs. My question is how do I determine if an input was just not provided or if the input provided was not a string?
I only want people to put an actual string. Not different types of data structures.
Examples
Valid: www.example.com/myfile.php?input1=hello&input2=bye
Valid: www.example.com/myfile.php?input1=hello
Valid: www.example.com/myfile.php?input2=hello
Valid: www.example.com/myfile.php
Invalid: www.example.com/myfile.php?input1[]
<?php
function check_valid($string) {
if (!is_string($string)) {
echo "This is a not string. We tested: ".$string."<br>";
} else {
echo "This is is string. We tested: ".$string."<br>";
}
}
$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>
You should use the isset() method to check if $input1 or $input2 are provided or not.
function check_valid($test) {
if (isset($test) && is_string($test)) {
echo "Valid";
return;
}
echo "Not Valid";
}
You can check if the value exists, containts empty or null.
<?php
function check_valid($string) {
if (trim($string) == NULL OR trim($string) == "") { //Will check if value without a space is null or empty
return "valid";
}
}
$input1 = check_valid($_GET['input1']);
$input2 = check_valid($_GET['input2']);
?>
I want to check if the data is match between array and the string.
Im trying to check if the string is equals to each other but the problem is the condition is returning false and both value of $subex2[1] and $subdat is IT100. I think the problem is you can't compare an array to a string. Can someone help me about this?
here's the code
$subex = $objPHPExcel->getActiveSheet()->getCell('D8')->getValue();
$subex2 = explode(":", $subex);
$q = "select * from class where id='$id'";
$r = mysql_query($q);
$data = mysql_fetch_array($r);
$subdat = $data['subject'];
if($subdat == $subex2[1]) {
echo "Data matched";
}else {
echo "Data doesn't matched";
}
As mentioned in the comments. One value has an space before it. You can solve this kind of problems like this:
if(trim($subdat) == trim($subex2[1])) {
echo "Data matched";
} else {
echo "Data doesn't matched";
}
for case sensitive issue, this trick should apply.
if(strtolower(trim($subdat)) == strtolower(trim($subex2[1]))) {
echo "Data matched";
} else {
echo "Data doesn't matched";
}
this test works fine
$subdat = "IT100";
$subex2[1] = "IT100";
if($subdat == $subex2[1]) {
echo "Data matched";
}
You are not comparing same string
You first use array_map and trim values, delete space, next use in_array, example
$subex2 = array_map('trim',$subex2);
if( is_array($subex2) ){
if(in_array($subdata, $subex2)){
echo "Data matched";
} else {
echo "Data doesn't matched";
}
}
It's always good to check if it's actually an array, with is_array
Reference in_array https://www.w3schools.com/php/func_array_in_array.asp
try this:
$isMatched = strval($subex2[1]) === strval($subdat) ?: false;
I'm working with Zend Framework. I want to check last part of link. my link is http://localhost/sports/soccer/page_id/776543233242
my last part of URL must have 12 or 11 digit , and I want first of that part start with 8 if 11 digit and start with 7 if 12 digit.
public function detailAction ()
{
$uri = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
if (substr(substr($uri, -12),1)=='7'){
echo "successfull";
}
else if (substr(substr ($uri , -11),8)=='0'){
echo "succ";
}
else {
echo "failed";
}
}
This should work for you:
<?php
$url = "http://localhost/sports/soccer/page_id/776543233242";
$part = basename($url);
if(strlen($part) == 11 && $part[0] == 8 || strlen($part) == 12 && $part[0] == 7)
echo "yes";
else
echo "no";
?>
Output:
yes
Use basename() function in php to get your last part of the url and then count the string.Check the no of word using strlen. Use the code below
public function detailAction ()
{
$url = Zend_Controller_Front::getInstance()->getRequest()->getRequestUri();
$url = "http://localhost/sports/soccer/page_id/776543233242";
$basename = basename($url);
if(strlen($basename) == 11 && $basename[0] == 8 || strlen($basename) == 12 && $basename[0] == 7){
echo "succ";
}
else{
echo "failed";
}
}
Hope this helps you
See parse_url. You can then get the path and split it on /.
function isValidUrl($url)
{
$elements = parse_url($url);
if ($elements === false) {
return false;
}
$lastItem = end(explode("/", $elements['path']);
return ((strlen($lastItem) == 12 && $lastItem[0] == '7') || (strlen($lastItem) == 11 && $lastItem[0] == '8'));
}
If you only want to get the number form your url I suggest you to use regex. in this case:
$url="http://localhost/sports/soccer/page_id/776543233242";
$regex = "/[0-9]+/";
preg_match_all($regex, $url, $out); //$out will be an array storing the mathcing strings, preg_match_all creates this variable to us
var_dump($out);
This code outputs the $out. It will look like this:
array(1) {
[0]=>
array(1) {
[0]=>
string(12) "776543233242"
}
}
I hope it will help you.
Obviously the part of the url desired corresponds to the page_id parameter.
With Zend Framework, you can do something like this to get the value of this parameter:
$page_id = $this->getRequest()->getParam('page_id');
if(strlen($page_id) == 11 && $page_id[0] == 8
|| strlen($page_id) == 12 && $page_id[0] == 7)
echo "yes";
else
echo "no";
This question already has answers here:
Equal string comparisons are failing
(2 answers)
Closed 8 years ago.
So i have been trying to compare two strings. One from a $_POST method , and one read from a text file. Although they seem to be the same when I print both of them, my strcmp() never returns 0 meaning that they are not equal. Why does my strcmp() function never return 0?
Here is the actual code :
$fileRead = 'Users.txt';
$wasRead = FALSE;
$handleRead = fopen($fileRead,'r');
$character = fread($handleRead,1);
echo"<p> ".$character." </p>";
fgets($handleRead);
while($character != 'Q')
{
$lineName = fgets($handleRead);
echo "<p> ".$lineName." </p>";
$linePassword = fgets($handleRead);
echo "<p> ".$linePassword." </p>";
$character = fread($handleRead,1);
echo"<p> ".$character." </p>";
fgets($handleRead);
$porfavor = $_POST['newUserId'];
$porfavor = strtolower($porfavor);
echo $porfavor."<br>";
echo $lineName."<br>";
//$comparison = strcmp($lineName." ",$_POST['newUserId']);
//echo $comparison;
$comparison = strcmp($porfavor,$lineName);
echo $comparison;
if($comparison == 0)
{
$character = 'Q';
echo "<p> User Already Exists </p>";
echo " Sing In";
echo "<br>";
}
}
fclose($handleRead);
You may have an invisible character in one of your strings. Try doing a var dump.
$comparison = strcmp($porfavor,$lineName);
if($comparison != 0){
echo "<pre>";
var_dump($porfavor);
var_dump($lineName);
exit;
}
some tips:
You may need to use trim() on your variables to account for whitespace;
consider using strtoupper() if either might vary in case. Keep in mind it's case sensitive.
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
Regular Expression matching for entire string
On my form page, I am trying to make it only accept alphanumeric characters for my username and password and require that they be from 6 to 15 characters. When I type in invalid data, it will insert it into the database rather than throw the user error that I defined in my CheckAlNum function.
functions.php
function checkAlNum($whichField)
{
if (preg_match('/[A-Za-z0-9]+/', $_POST[$whichField])){
if ( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 ))) {
$message1 = '<p> Username and password must be between 6 and 15 characters </p>';
return user_error($message1);
}
else{
return true;
}
}
else {
$message = '<p>Username and password can only be numbers or letters</p>';
return user_error($message);
}
}
Form.php
if (count($_POST) > 0) {
//Validate the inputs
$errorMessages = array();
//Validate the username
$item5 = checkAlNum('username');
if($item5 !== true) {
$errorMessages[] = $item5;
}
//Validate the password
$item6 = checkAlNum('password');
if($item6 !== true) {
$errorMessages[] = $item6;
}
//Validate the firstName and lastName
$item1 = checkNameChars('firstName');
if ($item1 !== true) {
$errorMessages[] = $item1;
}
$item2 = checkNameChars('lastName');
if ($item2 !== true) {
$errorMessages[] = $item2;
}
//Validate the office name
$item3 = checkOfficeChars('office');
if ($item3 !== true) {
$errorMessages[] = $item3;
}
//Validate the phone number
$item4 = validate_phone_number('phoneNumber');
if($item4 !== true) {
$errorMessages[] = $item4;
}
//Check to see if anything failed
if (count($errorMessages) == 0) {
$newEmployee = new Person;
$newEmployee -> insert();
}
else { //Else, reprint the form along with some error messages
echo "<h2><span>Error</span>: </h2>";
foreach($errorMessages as $msg) {
echo "<p>" . $msg . "</p>";
}
}
}
?>
I've tried playing around with the nesting of the if-else statements of the checkAlNum function and also the regex (although I'm pretty sure the regex is right). Maybe I'm just missing something really silly?
function checkAlNum($whichField)
{
if (preg_match('/^[a-z0-9]{6,15}$/i', $_POST[$whichField])) {
return true;
}
else {
$message = '<p>Username and password can only be numbers or letters, 6-15 characters long</p>';
return user_error($message);
}
}
Without the ^ and $ anchors, your regex only checks whether there are alphanumerics anywhere in the field, not that the whole thing is alphanumeric. And changing + to {6,15} implements the length check here, so you can remove that extra check in your code.
I think the second if statement is incorrect. It should be like this:
if ( !( (!count(strlen($whichField) >= 6)) OR (!count(strlen($whichField) <= 15 )) ) ) {
// ... do something
}
This is due to De Morgan Rule which states
A AND B = !( !A OR !B )
In any case, I would not do my checks this way, strucurally you will end up with too many nested if statements that are hard to maintain and make your code look unpretty. Try avoiding nested conditions in your code.
Barmar's answer is the best. But if you want to keep your if statement to check string length, you need to remove the count() as you are already checking the length using strlen().
if ( (!(strlen($whichField) >= 6)) OR (!(strlen($whichField) <= 15 ))) {