Check to see if EXACT value is in a string - PHP - php

I have read numerous posts about how to see if a value is in a string. Apparently my request is different since the multiple bits of code haven't worked 100%.
I am searching a string and need to make sure the EXACT value is in there - with a perfect match.
$list="Light Rain,Heavy Rain";
$find="Rain";
That should NOT match for what I need to do. I need it to match exactly.
All the code I have tested says it IS a match - and I understand why. But, what can I do to make it not match since Rain is different than Light Rain or Heavy Rain? I hope I am making sense.
I have already tried strpos and preg_match, but again, those equal a match - but for my purposes, not an equal match.
Thanks for something that probably will end up being a DUH moment.

If you need exact matches and the $list is always comma delimited. Why not check for them this way?
$list = explode(',', "Light Rain,Heavy Rain");
var_dump(in_array('Rain', $list)); // false
var_dump(in_array('Heavy Rain', $list)); // true
and if you must have a regular expression.
in your regex, make sure you're checking for the start of the string or a comma (^|,) at the start, and then your string, then another comma or the end of the string (,|$). The ?: makes them non-capturing groups so they dont show up in $matches.
$list = "Light Rain,Heavy Rain";
$test = 'Rain';
preg_match("/(?:^|,)($test)(?:,|$)/", $list, $matches);
var_dump(!empty($matches)); // false
$test = 'Heavy Rain';
preg_match("/(?:^|,)($test)(?:,|$)/", $list, $matches);
var_dump(!empty($matches)); // true

Try this:
$list="Light Rain,Heavy Rain";
$find="Light";
if(strpos($list,$find) !== false)
{
echo 'true';
}
else
{
echo 'false';
}
Credits to: https://stackoverflow.com/a/4366748/4660348

Related

check if array has this value and then grab it and place it an a variable

I have a string like the one below
20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424
I will explode it and it will then be turned into an array.
But I want to check if the array has Ref:675743957424 and then place it inside a variable like for example $a.
I want to do this since the string might change from one point to another so the position of Ref is not fixed.
How Can i obtain such thing?
Thanks.
Edited
I tried not exploding it but instead try grabbing the data see code below
<?php
$line = "20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424";
// perform a case-Insensitive search for the word "Vi"
if (preg_match("/\bRef\b/i", $line, $match)) :
print "Match found!";
//how can I grab the Ref part?
endif;
?>
You have to use:
preg_match ('/Ref:[\d]*/', $line, $matches);
The matches will be saved to variable $matches and then you can operate with said matches.
The RegExp, you just need to look for string Ref: followed by any amount of numbers (\d looks for any digit and * looks for zero or more ocurrences of the previous operator, digits in this case).
If you know the exact number of digits that you must to find and it is not varying you could use the pattern {NUMBER}, like:
preg_match ('/Ref:[\d]{12}/', $line, $matches);
This case, you are looking for 12 digits after Ref:.
You can use strpos() to check whether the substring present in the string. If it is true, you can assign that to your variabble. Pleas see the below code, it may help you.
$line = "20Nov 18:14:xxxxxxxxxx has given 10 points to xxxxx. New bitcoin collection Balance:XXXXXXXX. Ref:675743957424";
$string_to_check ='Ref:675743957424'
if (strpos($line,$string_to_check) !== false) { //Ref is present
$a = $line;
}

PHP trouble with preg_match

I thought I had this working; however after further evaluation it seems it's not working as I would have hoped it was.
I have a query pulling back a string. The string is a comma separated list just as you see here:
(1,145,154,155,158,304)
Nothing has been added or removed.
I have a function that I thought I could use preg_match to determine if the user's id was contained within the string. However, it appears that my code is looking for any part.
preg_match('/'.$_SESSION['MyUserID'].'/',$datafs['OptFilter_1']))
using the same it would look like such
preg_match('/1/',(1,145,154,155,158,304)) I would think. After testing if my user id is 4 the current code returns true and it shouldn't. What am I doing wrong? As you can see the id length can change.
It's better to have all your IDs in an array then checking if a desired ID is existed:
<?php
$str = "(1,145,154,155,158,304)";
$str = str_replace(array("(", ")"), "", $str);
$arr = explode(',', $str);
if(in_array($_SESSION['MyUserID'], $arr))
{
// ID existed
}
As your string - In dealing with Regular Expressions, however it's not recommended here, below regex will match your ID if it's there:
preg_match("#[,(]$ID[,)]#", $str)
Explanations:
[,(] # a comma , or opening-parenthesis ( character
$ID # your ID
[,)] # a comma , or closing-parenthesis ) character

Using PHP's preg_match to see if a value matches a list of values

I want to see if a variable contains a value that matches one of a few values in a hard-coded list. I was using the following, but recently found that it has a flaw somewhere:
if (preg_match("/^(init)|(published)$/",$status)) {
echo 'found';
} else {
echo 'nope';
}
I find that if the variable $status contains the word "unpublished" there is still a match even though 'unpublished' is not in the list, supposedly because the word 'unpublished' contains the word 'published', but I thought the ^ and $ in the regular expression are supposed to force a match of the whole word. Any ideas what I'm doing wrong?
Modify your pattern:
$pattern = "/^(init|published)$/";
$contain = "unpublished";
echo preg_match($pattern, $contain) ? 'found' : 'nope' ;
This pattern says our string must be /^init$/ or /^published$/, meaning those particular strings from start to finish. So substrings cannot be matched under these constraints.
In this case, regex are not the right tool to use.
Just put the words you want your candidate to be checked against in an array:
$list = array('init', 'published');
and then check:
if (in_array($status, $list)) { ... }
^ matches the beginning of a string. $ matches the end of a string.
However, regexes are not a magic bullet that need to get used at every opportunity.
In this case, the code you want is
if ( $status == 'init' || $status == 'published' )
If you are checking against a list of values, create an array based on those values and then check to see if the key exists in the array.

PHP match string, is fnmatch right for the job

I'm trying to figure out how I can compare values from an array against a particular string.
Basically my values look like chrisx001, chrisx002, chrisx003, chrisx004, bob001
I was looking at fnmatch() but I'm not sure this is the right choice, as what I want to do is keep chrisx--- but ignore bob--- so I need to wildcard the last bit, is there a means of doing this where I can be like
if($value == "chrisx%"){/*do something*/}
and if thats possible is it possible to double check the % value as int or similar in other cases?
Regex can tell you if a string starts with chrisx:
if (preg_match('/^chrisx/', $subject)) {
// Starts with chrisx
}
You can also capture the bit after chrisx:
preg_match('/^chrisx(.*)/', $subject, $matches);
echo $matches[1];
You could filter your array to return a second array of only those entries beginning whith 'chris' and then process that filtered array:
$testData = array ( 'chrisx001', 'chrisx002', 'chrisx003', 'chrisx004', 'bob001');
$testNeedle = 'chris';
$filtered = array_filter( $testData,
function($arrayEntry) use ($testNeedle) {
return (strpos($arrayEntry,$testNeedle) === 0);
}
);
var_dump($filtered);

Sorting through a delimited string with PHP

I am trying to create a script that checks if a certain value is in a comma delimited string, and if the value is present, it should return true else it should return false.
Basically, I am trying to check if a user has voted for a specific person before, and if so, they cannot vote again, if they have not, vote and then add their uid to the database.
I am using explode to get all the values into an array, but I am unsure about the checking function, I have a few ideas but this is quite an important script so I wanted to see if there is a better way of going about it.
$test = "john,jack,tom";
$exploded = explode(",",$test);
$hostID = "john";
foreach($exploded as $one){
if($one == $hostID){
$return = TRUE;
}else{
$return = FALSE;
};
};
Thanx in advance!
You could use in_array.
Some people prefer to use lowercase true and false.
The semicolon after } is not needed
$return = TRUE does not actually stop the function. Maybe you do return $return.
Some people like to put spaces after comma's and keywords (e.g. foreach, if, else)
Some people prefer single quotes over double quotes
Code:
function find_name($name, $list)
{
$exploded = explode(',', $list);
return in_array($name, $exploded);
}
var_dump(find_name('john', 'john,jack,tom'));
?>
As Sjoerd says, in his very good advice.
function find_name( $needle , $haystack ) {
if( strpos( $haystack , $needle )===false )
return false;
return in_array( $needle , explode( ',' , $haystack ) );
}
Test cases:
// find_name( 'john' , 'peter,mark,john' );
true
// find_name( 'peter' , 'mark,john' );
false
EDITED: As per advice from Gordon.
You could also use
strpos — Find position of first occurrence of a string
instead:
return strpos('john,jack,tom', 'barney'); // returns FALSE
Note that the function returns the position if the string was found, so searching for john will return zero, which would be FALSE if you compare it for equality (==). In other words use the identity comparator (===).
As Lucanos correctly points out, there is chance to get false positives when using strpos if the searched name is part of a longer name, e.g. searching for jean only would also find jean-luc. You could add a comma at the end of the haystack string and search for jean, though, but then again, it feels hackish. So it's likely better to use in_array.

Categories