PHP in_array Find Any Matches - php

I am trying to figure out how to match any words within an array. For example, the code bellow works for finding "Test Name" within an array but does not find "Another Test Name" (due to the word "Another") within the array. Any ideas?
if (in_array($html[$i], $eventsarray))
{
$topeventaa = "yes";
}
else
{
$topeventaa = "no";
}

Taken from http://php.net/manual/en/function.in-array.php
<?php
/**
* Takes a needle and haystack (just like in_array()) and does a wildcard search on it's values.
*
* #param string $string Needle to find
* #param array $array Haystack to look through
* #result array Returns the elements that the $string was found in
*/
function find ($string, $array = array ())
{
foreach ($array as $key => $value) {
unset ($array[$key]);
if (strpos($value, $string) !== false) {
$array[$key] = $value;
}
}
return $array;
}
?>

If you want to match any of the words to those in your array, you may want to use explode on your string and then check each token as you do in your example.

We probably need more information, but you can create variable with the pattern matching you need with preg_match and pass it as the argument in your search.
preg_replace and str_replace may be helpful, depending on what exactly you're trying to accomplish.

You may want to look into recursive function calls, like when traversing through all the directories within a directory tree.
I'd splice the array up to the index where it was found, leaving the remainder to be passed back into the same function to search through again.
Depending on what results you want from knowing the number of occurrences of words within a string could we then start to break down the problem and write some code.

Justin, there's no direct way--no existing built-in function--to do what I believe you seek; you must iterate over the array yourself, along the lines of
$topeventaa = "no";
for ($eventsarray as $key=>$value){
if (0 <= strpos($html[$i], $eventsarray[$key])) {
$topeventaa = "yes";
break;
}
}

Use preg_grep instead of in_array to find all elements of an array matching a given pattern.

Related

Function Will Not Detect String Included In Array Value

I have a little piece of code in PHP that returns certain key-value pairs based upon if a value contains /includes a specific value: Code Runnable number 1
$example = array('1'=>'if you dont','2'=>'if you like','3'=>'if you know');
$searchword = 'like';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
print_r($matches);
The function works perfectly if the array's value's words are separated, like above. The above code will return an array with all the key-value pairs with a value that includes $searchword. However, if the array's value's words aren't separated, like the below, the function will seemingly not detect the word inside the value(that is inside the array), therefore returning a blank array: Code Runnable number 2
$example = array('1'=>'ifyoudont','2'=>'ifyoulike','3'=>'ifyouknow');
$searchword = 'like';
$matches = array_filter($example, function($var) use ($searchword) { return preg_match("/\b$searchword\b/i", $var); });
print_r($matches);
How could I make the code detect if a value inside an array includes a specific string, even if the value's contents aren't spaced? I have tried searching and many other solutions and nothing seems to be working.
REGEX in this scenario are overkill, instead you can use strpos:
$matches = array_filter($example, function($var) use ($searchword) { return strpos($var,$searchword) !== FALSE; });
Incidentally, you don't need to use array_filter. There's already a function that filters an array based on a pattern.
$matches = preg_grep("/$searchword/", $example);
But if you aren't going to be using word boundaries, I agree with the other answer that you don't need to use a regular expression at all.
Just get rid of the word boundary \b from your regex:
return preg_match("/$searchword/i")

Find if user search is within a part of any array fields

I'm trying to figure out a way to see if user entered search term relates to anything in the $propertyData array.
So far I have used in_array() function, but to my understanding it will only match if user entered search term matches array field exactly e.g. User entered "This is a house" and it matches first field in an array wich is "This is a house", but if user enters "This is a" or "a house" it will not match, even though these words are present in that field.
if(in_array($getSearch, $propertyData)) {
// $getSearch is user input
// $propertyData is array containing fields
}
Is there a function / way that can be used to achieve a task?
Try preg_grep(). It searches an array by regular expression and returns an array of values that matched the expression. So if anything other than an empty array is returned it is considered true:
if(preg_grep("/$getSearch/", $propertyData)) {
For case insensitive add the i modifier:
if(preg_grep("/$getSearch/i", $propertyData)) {
If you want an array of all of the values that matched (if more than 1) also, then:
if($matches = preg_grep("/$getSearch/i", $propertyData)) {
Use array_filter() in conjunction with strpos() scan your array for partial matches of the search-string and return items where a match is found:
$result = array_filter($array,
function ($item) use ($getSearch) {
return (strpos($item, $getSearch) !== FALSE);
},
$propertyData);
Alternatively, you could use preg_grep() as suggested in AbraCadaver's answer. It returns an array consisting of the elements of the input array that match the given pattern. The regular expression needs to be enclosed in delimiters. I've used / below:
// escape search pattern to allow for special characters
$searchPattern = preg_quote($getSearch, '/');
if ($arr = preg_grep("/$searchPattern/", $propertyData)) {
print_r($arr);
// ...
}
You can use something like this:
$found = FALSE;
foreach($propertyData as $property) {
if(strpos($userQuery, $property)) {
$found = TRUE;
break;
}
}
However, if $propertyData grows, this solution will get slow. Then you could use a database for this.
Use:
foreach($propertyData as $data )
{
if( strpos($data, $getSearch) )
{
//match found
}
}

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);

Check if any value in an array exists within a haystack string

I have a string like abcdefg123hijklm. I also have an array which contains several strings like [456, 123, 789].
I want to check if the number in the middle of abcdefg123hijklm exists in the array.
How can I do that? I guess in_array() won't work.
So you want to check if any substring of that particular string (lets call it $searchstring) is in the array?
If so you will need to iterate over the array and check for the substring:
foreach($array as $string)
{
if(strpos($searchstring, $string) !== false)
{
echo 'yes its in here';
break;
}
}
See: http://php.net/manual/en/function.strpos.php
If you want to check if a particular part of the String is in the array you will need to use substr() to separate that part of the string and then use in_array() to find it.
http://php.net/manual/en/function.substr.php
Another option would be to use regular expressions and implode, like so:
if (preg_match('/'.implode('|', $array).'/', $searchstring, $matches))
echo("Yes, the string '{$matches[0]}' was found in the search string.");
else
echo("None of the strings in the array were found in the search string.");
It's a bit less code, and I would expect it to be more efficient for large search strings or arrays, since the search string will only have to be parsed once, rather than once for every element of the array. (Although you do add the overhead of the implode.)
The one downside is that it doesn't return the array index of the matching string, so the loop might be a better option if you need that. However, you could also find it with the code above followed by
$match_index = array_search($matches[0], $array);
Edit: Note that this assumes you know your strings aren't going to contain regular expression special characters. For purely alphanumeric strings like your examples that will be true, but if you're going to have more complex strings you would have to escape them first. In that case the other solution using a loop would probably be simpler.
You can do it reversely. Assume your string is $string and array is $array.
foreach ($array as $value)
{
// strpos can return 0 as a first matched position, 0 == false but !== false
if (strpos($string, $value) !== false)
{
echo 'Matched value is ' . $value;
}
}
Use this to get your numbers
$re = "/(\d+)/";
$str = "abcdefg123hijklm";
preg_match($re, $str, $matches);
and ( 123 can be $matches[1] from above ):
preg_grep('/123/', $array);
http://www.php.net/manual/en/function.preg-grep.php

stristr Case-insensitive search PHP

Please excuse my noob-iness!
I have a $string, and would like to see if it contains any one or more of a group of words, words link ct, fu, sl** ETC. So I was thinking I could do:
if(stristr("$input", "dirtyword1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
elseif(stristr("$input", "dirtyWord1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord2");
}
...ETC. BUT, I don't want to have to keep doing if/elseif/elseif/elseif/elseif...
Can't I just do a switch statement OR have an array, and then simply say something like?:
$dirtywords = { "f***", "c***", w****", "bit**" };
if(stristr("$input", "$dirtywords"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
I'd appreciate any help at all
Thank you
$dirty = array("fuc...", "pis..", "suc..");
$censored = array("f***", "p***", "s***");
$input= str_ireplace($dirty, $censored , $input);
Note, that you don't have to check stristr() to do a str_ireplace()
http://php.net/manual/en/function.str-ireplace.php
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search.
Surely not the best solution since I don't know too much PHP, but what about a loop ?
foreach (array("word1", "word2") as $word)
{
if(stristr("$input", $word))
{
$input = str_ireplace("$input", $word" "thisWillReplaceDirtyWord");
}
}
When you have several objects to test, think "loop" ;-)

Categories