PHP - preg_match alternative - php

I'm using preg_match() in PHP to detect queries related to weather. However, it detects a match for the string if it is inside another string. For example, "mayweather" will evaluate to true.
<?php
$q = "floyd mayweather";
if(preg_match('(weather|forecast|temperature)', $q) === 1) {
echo "match";
}
?>
What should I use instead of preg match? I only want it to detect the words "weather", "forecast", and "temperature", but NOT "mayweather", which is a string inside a string.

You can use the \b word boundary tag to indicate that you want to match full words only. Something like this:
preg_match('/\b(weather|forecast|temperature)\b/i', $q)

Related

how to use php to check if a variable contains a group of characters

i have a variable and i want to use php to check if it contains a group of characters
i would like the code to be like this
$groupofcharacters = ["$","#","*","("];
if($variable contains any of the letters in $groupofcharacters){
//do something}
i know that this will need the use of strpos() function but how can i use the strpos function to check if a variable contains a group of characters without me having to create a strpos() function for all the characters that i want to check for.
please if you don't understand you can tell me in the comments
Best way to solve your issue is by using RegEx. Try this:
<?php
$variable = 'Any string containing $*(#';
$sPattern = '/[$#*(]/';
if (preg_match($sPattern, $variable)) {
// Do something
}
You can use strpbrk to achieve this. The doc says:
strpbrk — Search a string for any of a set of characters
Returns a string starting from the character found, or FALSE if it is not found.
Snippet:
<?php
if(strpbrk($variable,"$#*(") !== false){
// your logic goes here
}
check if it has any char. Using strpos
First you need to combine the array as string after check ot if there's one of them in the
$groupofcharacters = ["$","#","*","("];
$strs = implode("", $groupofcharacters);
foreach(str_split($variable) as $s) {
if (strpos($s, $strs)) {
echo "it contains "; continue;
}
}

How to use character classes in searching a string in PHP

Using a for loop, I want to cycle through each character in a string and check to see if it is a certain letter. Let's say I want to search my string for my favorite letters -- A,C,D,O,V. Let's say I have a string, $giantButtText. Why does this result in no output on my standard output (given that $giantButtText does indeed contain those letters)?
if($giantButtText[$i] == "/[acdov]/") echo $giantButtText[$i];
Cheers!
You are trying to match $giantButtText[$i] to a regular expression.
The standard way to do this is preg_match() (http://php.net/manual/en/function.preg-match.php).
Something like this should work:
$a = array();
$a[0] = "dadov";
if (preg_match("/[acdov]/", $a[0])) echo "true";
-> true

How to match any thing dosen't contain a specific word using RegExp

How to match any thing dosen't contain a specific word using RegExp
Ex:
Match any string doesn't contain 'aabbcc'
bbbaaaassdd // Match this
aabbaabbccaass // Reject this
If you're just after this sequence of characters, don't use a Regular Expression. Use strpos().
if (strpos('aabbaabbccaass', 'aabbcc') !== false) {
echo 'Reject this.'
}
Note: Be sure to read the warning in the manual about strpos() return values.
You can use negative lookahead:
(?!.*?aabbcc)^.*$
Live Demo: http://www.rubular.com/r/4Exbf7UdDv
PHP Code:
$str = 'aabbaabbccaass'; //or whatever
if (preg_match('/(?!.*?aabbcc)^.*$/', $str))
echo "accepted\n";
else
echo "rejected\n";
try this to avoid some sequences of letters :
^((?!aabbcc).)*$
try this:
if(preg_match('/aabbcc/', $string) == 0) {
[ OK ]
}
else {
[ NOT OK ]
}
You can use this to describe a substring that doesn't contain aabbcc:
(?>[^a]++|a(?!abbcc))*
for the whole string, just add anchors (^ $)

String filtering in php with preg_match and regular expression

I am creating a simple checker function in PHP to validate strings before putting them into an SQL query. But I can not get the right results the from the preg_match function.
$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
echo $tv;
Sometimes nothing echoed to the source code, not even a false value... I want to get 1 as the result of this call, because $myval only contains lowercase alphanumerics and numbers.
So is there any way in php to detect if a string only contains lowercase alphanumerics and numbers using the preg_match function?
Yes, the circumflex goes outside the [] to indicate the start of the string, you probably need an asterisk to allow an arbitrary number of characters, and you probably want a $ at the end to indicate the end of the string:
$tv = preg_match('/^[a-z0-9]*$/', $myval);
If you write [^a-z] it means anything else than a-z.
If you want to test if a string contains lowercase alphanumerics only, I would present your code that way to get the proper results (what you wrote already works):
$myval = "srg845s4hs64f849v8s4b9s4vs4v165";
$tv = preg_match('/[^a-z0-9]/', $myval);
if($tv === 0){
echo "the string only contains lowercase alphanumerics";
}else if($tv === 1){
echo "the string does not only contain lowercase alphanumerics";
}else{
echo "error";
}

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.

Categories