How to use character classes in searching a string in PHP - 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

Related

PHP - preg_match alternative

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)

Can we use Bitwise operator "|" with strpos in php?

Can we use Bitwise operator "|" with strpos in php?
I need to check if a0,a1,a2,a5 strings are exists in the given $status variable.
My code is given bellow.My code will return values(position) only when the status variable have value=a0 or a1 or a2 or a5.It will return false when $status='a1 test string.
$status='a1 test string';
echo strpos("|a0|a1|a2|a5|", $status);
No, you cannot. Documentation does not mention anything remotely similar:
strpos — Find the position of the first occurrence of a substring in
a string
Find the numeric position of the first occurrence of needle in the
haystack string.
Parameters
haystack The string to search in.
needle If needle is not a string, it is converted to an integer and
applied as the ordinal value of a character.
offset If specified, search will start this number of characters
counted from the beginning of the string. If the offset is negative,
the search will start this number of characters counted from the end
of the string.
In fact, it wouldn't make much sense to implement such feature since you already have a full-fledged regular expression engine:
$has_substrings = (bool)preg_match('/a0|a1|a2|a5/u', $status);
You can use it like this. Here | means or
<?php
$status='a1 test string';
if(preg_match("/\b(a0|a1|a2|a5)\b/", $status))
{
echo "Matched";
}
Can we use Bitwise operator "|" with strpos in php?
as a Bitwise operator | - No
as a literal symbol | - Yes
You cannot do that with a single string search. You need to use either a regular expression which can test for multiple options at once, or you need to iterate over your search terms.
Sahil Gulati gave a simple example for a regular expression based approach.
Here is a simple iteration based approach:
<?php
$status = 'a1 test string';
$search = explode('|', substr("|a0|a1|a2|a5|", 1, -1));
// would be much easier to start with an array of search tokens right away:
// $search = ['a0', 'a1', 'a2', 'a5'];
$result = false;
array_walk($search, function($token) use ($status, &$result) {
$result = (FALSE!==strpos($status, $token)) ? true : $result;
});
var_dump($result);

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.

check for number anywhere in a string

$vari = "testing 245";
$numb = 0..9;
$numb_pos = strpos($vari,$numb);
echo substr($vari,0,$numb_pos);
The $numb is numbers from 0 to 9
Where am I wrong here, all I need to echo is testing
You want to cut out the numbers from a string?
$string = preg_replace('/(\d+)/', '', 'String with 1234 numbers');
Use a regular expression to strip numeric characters from your string.
or, use a regular expression to find the first instance of one either way...
Your code won't work as-is, as it'll fail if the number if the first character in the string. (You need to check $numb_pos !== false prior to the substr.)
Irrespective, if you just want to check for the existance of a number in a string, something like the following would probably be more efficient.
$digitMatched = preg_match('/\\d/im', $vari);

Categories