I need to check if $string1 is like $string2 but I dont want it to matter if one text is different than the otherif it starts with the same string. For example I would like
if (admin.example2 == admin.example1)
should return true! What's the best way to do this?
My exact requirement. An if condition to check if any string is starting with admin is present in the array.
if ($client_name like 'admin') {
...
...
}
There is unlimited number of entries in an array. I just want to check if any string is present which start with "admin" is there or not.
Seems like you are looking for similar_text in PHP
<?php
similar_text("admin.example2", "admin.example1", $simpercentage);
if($simpercentage>90)
{
echo "Both strings are like ".round($simpercentage)."% similar.";
}
OUTPUT :
Both strings are like 93% similar.
Just set a percentage ratio (in the above case I have set it like 90% similarity) , You can adjust like as per your needs. The code will return 100% match if both strings are admin.example2 and admin.example2 (If both the strings are same)
As the question was edited drastically...
<?php
$arr=['admin1','administrator','admin2','I am an admin','adm','ADMIN'];
array_map(function ($v){ if(stripos(substr($v,0,5),'admin')!==false){ echo "$v starts with the text admin<br>";}},$arr);
OUTPUT :
admin1 starts with the text admin
administrator starts with the text admin
admin2 starts with the text admin
ADMIN starts with the text admin
According to your new specified requirement, if a string starts with 'admin' can be checked like this:
$your_string = 'admin.test';
if(strcmp(substr($your_string, 0, 5), "admin") == 0)
{
echo 'begins with admin';
} else {
echo 'does not begin with admin';
}
EDIT:
If you have an array of strings, example $array = array("admin.test", "test", "adminHello", "hello"), you could make a function that checks if the array contains at least one string that begins with admin:
function checkArrayStartsWithAdmin($array)
{
$result = false;
foreach($array as $key => $value)
{
if(strcmp(substr($value, 0, 5), "admin") == 0)
{
$result = true;
break;
}
}
return $result;
}
You should probably want to take a look at the concept of the levenshtein distance.
You could use this php function.
http://www.php.net/manual/es/function.levenshtein.php
I hope it helps you.
Related
So I'm working on a PHP app receiving a student ID from an input and searching through a file to find if the ID is present or not. If it's present, the name of the student and whether hes present or not should be printed out, and if the ID doesn't exist, it should say that there are no students with this ID.
Here is an example of what the txt file looks like:
1234|Sally Simon|1
4321|Larry Lonbottom|0
7364|Hannah Harrow|1
I made a solution and tested it, but it prints out a student name even when the ID I enter is false. Could someone give me an idea of what I'm doing wrong?
Here is my code:
<?php
$student=$_GET["student"];
$lines = file('students.txt');
foreach ($lines as $line){
$var = explode("|", $line);
}
if($student == $var[0] || $var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($student == $var[0] || $var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}else{
echo "No students with that id!";
}
?>
1) Your $var will always have the last line in the file, wrap everything with the foreach;
2) You should use && instead of ||
EDIT: updated code
<?php
$student=$_GET["student"];
$lines = file('students.txt');
$missing = true;
foreach ($lines as $line){
$var = explode("|", $line);
if($student == $var[0]){
$missing = false;
if($var[2] == "1"){
echo "$var[1]($var[0]): has signed up";
}else if($var[2] == "0"){
echo "$var[1]($var[0]): hasn't signed up";
}
}
}
if($missing){
echo "No students with that id!";
}
?>
As OPs said you need to change your conditional logic (if elses) and place it within the foreach loop (i.e. before the foreach's closing }.
However: (php.net file) "Each element of the array corresponds to a line in the file, with the newline still attached." so you have to remove the EOL/NL marker (invisible whitespace) from $var[2]. This can be achieved changing your file function to file('students.txt', FILE_IGNORE_NEW_LINES) however it is probably best to use trim as per example below.
It may help simplify things for you if you get rid of else conditions. try this:
<?php
$student=trim($_GET["student"]); // should also check and exit if ! digits
$lines = file('students.txt');
$isRegistered = array( "hasn't signed up", "has signed up");
$invalidID = TRUE;
foreach ($lines as $line){
$var = explode("|", $line);
if( $student == trim($var[0]) ) {
echo "$var[1]($var[0]): " . $isRegistered[ trim($var[2]) ];
$invalidID = FALSE;
break; // prevent unnecessary processing, exit foreach loop
}
}
if ( $invalidID ) echo "No students with that id!";
?>
Note: the above assumes file only contains valid content.
(1) Put the if statements inside the loop since you want to use those conditionals with every line.
(2) You are using logical 'or' operators. This means that only one of the conditions for that line need to be met.
This is what you are saying
if $student == $var[0] OR if $var[2] == 1
So regardless of what ID you enter, you always match the 0 or 1 condition.
Use the && operator instead of || if you need both conditions to be met instead of just one of the two.
(3) By using the == operator, the string will have to match with the value you are looking for exactly. You might have spaces in $student or there might be additional character in between the |. Just to air on the side of caution, remove all chances of there being hidden whitespace with your variables.
Do this: $student[0] = preg_replace('/\s+/', '', $student[0]); and do that with var[0] and var[2] as well. Do this before you run them through the if statements but still inside the loop.
Here is a link that talks about logical operators in php. It might be nice to use as a reference for future conditional statements that you need to build!
This link explains what you are doing to these values with preg_replace. It becomes very handy when you need to remove characters from a string that otherwise might difficult to deal with.
This is a simple code I can't figure out
if(preg_match( "/where/","where's my backpack") == true){
echo "this is a match";
// this is the part i cant figure out
// how can I store it as == $match1
// I tried $match1 == "this is a match"; but it didn't work
}else{
//$match1= " "; << this what I tried and didn't work
//when I say echo match1 later, it displays this is a match even when its wrong
}
how can I store it as a variable or something for later. for example, if those two matches are true, store it as $match1 so that I can later say 'echo $match1' so that it displays "this is a match". if not just display a space.
the overall code is in php BTW
== operator checks for equality, to store something you need to use =
$match1 = '';
if(preg_match("/where/", "where's my backpack"))
$match1 = "this is a match";
else
$match1 = " ";
echo $match1;
You can assign it directly:
$match = preg_match("/where/","where's my backpack") === 1
Now you have a boolean value that you can use anywhere after this statement.
Note that I have replaced your true with 1 as that is what preg_match will return but either will work.
By the way, I realize that this is not exactly what you want but I find it easier to maintain and more reusable when I separate output texts from logic like this.
Here is my question: I am trying to create a random bar code for my application. I want to check that if that code is already in the column, then generate a new number. Check it again. If it's unique, return it to the caller, else generate again.
I am using a recursive function for this purpose. I have added numbers 1,2,3,4 inside my database so every time it runs. It has to show me 5,6,7,8,9 or 10.
Here is my function:
function generate_barcode(){
$barcode = rand(1,10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if($bquery==1){
generate_barcode();
}else{
return $barcode;
}
}
And I just tested it like this:
$a = generate_barcode();
if(isset($a))
{
echo $a;
}
else
{
echo 'Not Set';
}
So the problem is that it is sometimes showing me "Not Set", but I want it to always generate a unique number. I am not inserting the data, so it's not a problem that all of the numbers are reserved.
Someone just guide me and let me know what is wrong with the code. I can use other approaches to do that, but I need to know what is wrong with the supplied code.
You need to return the generated number from your recursive call too, like:
function generate_barcode() {
$barcode = rand(1, 10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if ($bquery == 1) {
return generate_barcode(); // changed!
}
else {
return $barcode;
}
}
(You should include some kind of exit for the case that all numbers are 'taken'. This current version will call itself recursively until the PHP recursion limit is reached and will then throw an error.)
A return statement passes a value back to the immediate caller of the current function's call-frame. In the case of recursion, this immediate caller can be another invocation of that same function.
You can counter this by doing the following:
Change:
generate_barcode();
to:
return generate_barcode();
Do it like this:
$hash = md5( microtime().rand(0, 1000) );
Adding a time component means it will pretty much be unique. Unless you have like 32^32 of them.
If it has to be just numbers, just use the pkey and add like 10000 on to it for looks. or such.
After careful analysis - there is nothing wrong with it, but:
$a = generate_barcode();
if(isset($a)) <<< this bit
See you return the unique value and then you say it's isset my unique value, and $a will always be set, because if it's not you recurse the function until it is, and then you return it. Therefore it is always set...
You are trying to do:
while(true) {
$barcode = rand(1,10);
$bquery = mysql_num_rows(mysql_query("SELECT * FROM stock_item WHERE barcode='$barcode'"));
if($bquery===0){
break;
}
}
echo $barcode;
However, this will obviously only work for 10 bar codes and leading to an endless loop after that - meaning it is not the right approach to create a large number of bar codes.
Instead I would suggest to use an auto_increment to generate the bar code.
Btw, the mysql extension is deprecated. Use mysqli or PDO for new code.
I am trying to get multiple value from user input from text field and want to explode or keep adding into if condition statement
Here is my code
foreach ($list['post'] as $item) {
if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ){
$this->list_post($item);
}
}
Now what exactly I am looking for is in if( ($item['single']['catid'] != 8) AND ($item['single']['catid'] != 4) ) I want allow user to add multiple category ID and each ID will add AND and further id code AND ($item['single']['catid'] != 4)
I never done this before and don't know either this is proper way to do or any other possible better way.
Thanks a lot
You should have some kind of an array of the category IDs you want to check for, for example:
$categories = array(8, 4);
Then you could use something like the in_array(needle, haystack) built-in function of PHP.
Your if condition would become like that one: if (!in_array($item['single']['catid'], $categories)) {.
You should be using the above, but I am going to give you an idea of how it works, so you can understand the principle for more complex issues:
function exists($target, $array) {
foreach ($array as $element) { // Go through each element in the array
if ($element == $target) { // Check to see if any element there is what you are searching for
return true; // Return true, that it does exist, and stop there.
} else {
// Just ignore it...
}
}
return false; // If you get here, it means nothing returned true, so it does not exist...
}
To be used as if (exists($item['single']['catid'], $categories)) {.
It wouldn't work if it was "inside" the if statement because you have to do some processing before evaluating if it exists or not. So you either could have done that before the if statement, and store the result in a variable, or use a function (which PHP provides).
Hopefully the concept will help you fir more complex problems...
Note: this assumes your input is in the form of an array, which you can build via various ways, if not provided as is directly.
Update:
The input you get via the input field is sent through form, to which you specify either POST or GET as a method. Assuming it is POST that you are using, this is how you'd get the input as a string as it was entered in the text field:
$categories_string = $_POST['the_name_field_in_the_input_tag'];
After that you have to understand it as a list of items, let's say separated by commas: 1,3,5,8. Then this is simply separating by commas. You can use explode($delimiter, $string). Like that:
$categories_array = explode(',', $_POST['categories']);
But you cannot trust the input, so you could get something like 1, 2, 3,5,6. The spaces will mess it up, because you will have spaces all around. To remove them you can use trim for example.
$categories = array(); // Create the array in which the processed input will go
foreach ($categories_array as $c) { // Go through the unprocessed one
$categories[] = trim($c) * 1; // Process it, and fill the result. The times one is just so that you get numbers in the end and not strings...
}
Then you can use it as shown earlier, but keep in mind that this is just an example, and you might not even need all these steps, and there are much more efficient ways to process this input (regular expressions for example). But the concern here is not sanitizing input, but keep in mind you will need to do that eventually.
Hope it's clear enough :)
You might be better off with in_array() for checking a value against a variable number of possibilities.
I'm not sure I understand your problem. You want user to be able to input different values, e.g.:
$string = "5, 6, 7, 8, 10";
Afterwards, you want to check if 'catid' is not in that array and if it isn't you want to run $this->list_post($item);
If so, then you should use something like this:
$values = explode(", ", $string); //make array from values
foreach ($list['post'] as $item) {
if (!in_array($item['single']['catid'], $values)) { //check whether catid is in array
$this->list_post($item); // execute whatever you want
}
}
Hope it helps.
I have a list of postcode areas (left hand part only) as below:
IV1-28,IV30-32,IV36,IV40-49,IV52-56,IV63,KW1-3,KW5-14,PA21-38,PH1-26,PH30-41,PH49-50,LD1-99,SY16-20,SY23-25
My input is a UK Postcode eg. IV21
I need a PHP function to check if the input postcode (eg IV21) is in the list.
This would be simple enough, but the list is in the form IV1-28 as opposed to being a 'normal' list such as IV1,IV2,IV3,IV4,IV5,IV6...IV26,IV27,IV28 etc.
Help is much appreciated. Thanks in advance.
loops through an array of codes and splits them into the number then checks if that number is within the range
$list = array("IV1-28","AB1-10");
$found = false;
$input = "AB10";
$inputCode = substr($input,0,2);
$inputNumber = substr($input,2);
foreach ($list as $l)
{
$lCode = substr($l,0,2);
$lNumber = substr($l,2);
$listNumbers = explode("-",$lNumber);
if (($inputNumber >= $listNumbers[0]) && ($inputNumber <= $listNumbers[1]) && ($inputCode==$lCode))
{
$found = true;
break;
}
}
var_dump($found);
http://php.net/manual/en/function.explode.php (to split your list into only the left hand side), add the left hand side into an array, and use http://php.net/manual/en/function.in-array.php - should get you somewhere close to what you need
use strpos function. returns int if found or else false. note that matching IV1 would give true even of IV11 is found. so use the following script
$code="IV21";
$list="IV1-..........etc";
if(strpos($list,$code."-") || strpos($list,$code.",") {
//true
}
else {
//false
}
the "-" and "," is to ensure that the string ends so that IV11 won't give true if we search for IV1