check if two arrays contain similar values - php

is there a way to check if two arrays have value that is alike, note not equal but alike. something similar to what mysql has with LIKE to find words that is similar.
in topten.txt i have the following word:
WORKFORCE
in company.txt i have the following url:
Workforce-Holdings-Ltd
So basically i would like to search for the word WORKFORCE in company.txt and the results output should be Workforce-Holdings-Ltd.
Is it possible to do it.
i was maybe thinking preg_grep() perhaps?

Preg_grep is perfect for this. As long as you are searching array values you can just do something like the following:
<?php
$companies = [
'acme inc',
'wORkForce-holdings-ltd'
];
$search = 'WORKFORCE';
var_dump(preg_grep('/' . preg_quote($search, '/') . '/i', $companies));
Here's an ideone example.

You need not use preg match. Instead you can use strpos like:
$result=array();
$a=array('WORKFORCE');
$b=array('Workforce-Holdings-Ltd');
foreach($a as $array1){
foreach($b as $array2){
if (strpos(strtolower($array2),strtolower($array1)) !== false) {
$result[] = 'true';
}
else {
$result[] = 'false';
}
}
}
This will give you an array with true if match is ok or false is match is not ok for all array elements

Related

How to Get Multiple values can become single using php

I am a new person in the PHP. I have one String.I use this to find a word for strpos function
for example..
$a= "google" ;
$b= "google is best one" ;
if(strpos($b, $a) !== false) {
echo "true, " ; // Working Fine...
}
so i want to in this case check My Example
$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;
if(strpos($b, $a) !== false) {
echo "true, " ; // I Need True...
}
This is how you do PHP
Split the string on the comma using explode() and then check each of the parts individually:
$a= "google,yahoo,Bing" ;
$b= "Bing is Good " ;
$parts = explode(',', $a);
foreach ($parts as $part) {
if(strpos($b, $part) !== false) {
echo "true, " ; // I Need True...
}
}
To clarify, it looks like you're trying to perform a match such that any value in a list of values from $a is present in $b. This is not possible with a simple strpos() call because strpos() looks for the exact occurrence of the string you're passing in.
What you're attempting to do is a pattern-based search. To make this work, please look into using a regular expression with preg_match(). Such an example could look like this:
$pattern = '/google|yahoo|Bing/';
$target_string = 'Bing is good';
if(preg_match($pattern, $target_string)) {
echo "true, ";
}
For more information, look into regular expression syntax and play around with it until you're familiar with how they work.
Like Patrick Q said put names in an array example is here
becuase you are searching all three words "google,yahoo,Bing" which can not be true.
but for beginner to understand other way.
$a[0]= "google";
$a[1]= "yahoo";
$a[2]= "Bing";
$b= "Bing is Good";
strpos($b, $a[0]); // false
strpos($b, $a[1]); // false
strpos($b, $a[2]); // true as Bing found
also you can loop through to check
You can solve your issue with a regular expression:
if (preg_match('/string1|string2|string3/i', $str)){
//if one of them found
}else{
//all of them can not found
}

PHP - How to search an associative array by matching the key against a regexp

I am currently working on a small script to convert data coming from an external source. Depending on the content I need to map this data to something that makes sense to my application.
A sample input could be:
$input = 'We need to buy paper towels.'
Currently I have the following approach:
// Setup an assoc_array what regexp match should be mapped to which itemId
private $itemIdMap = [ '/paper\stowels/' => '3746473294' ];
// Match the $input ($key) against the $map and return the first match
private function getValueByRegexp($key, $map) {
$match = preg_grep($key, $map);
if (count($match) > 0) {
return $match[0];
} else {
return '';
}
}
This raises the following error on execution:
Warning: preg_grep(): Delimiter must not be alphanumeric or backslash
What am I doing wrong and how could this be solved?
In preg_grep manual order of arguments is:
string $pattern , array $input
In your code $match = preg_grep($key, $map); - $key is input string, $map is a pattern.
So, your call is
$match = preg_grep(
'We need to buy paper towels.',
[ '/paper\stowels/' => '3746473294' ]
);
So, do you really try to find string We need to buy paper towels in a number 3746473294?
So first fix can be - swap'em and cast second argument to array:
$match = preg_grep($map, array($key));
But here comes second error - $itemIdMap is array. You can't use array as regexp. Only scalar values (more strictly - strings) can be used. This leads you to:
$match = preg_grep($map['/paper\stowels/'], $key);
Which is definitely not what you want, right?
The solution:
$input = 'We need to buy paper towels.';
$itemIdMap = [
'/paper\stowels/' => '3746473294',
'/other\sstuff/' => '234432',
'/to\sbuy/' => '111222',
];
foreach ($itemIdMap as $k => $v) {
if (preg_match($k, $input)) {
echo $v . PHP_EOL;
}
}
Your wrong assumption is that you think you can find any item from array of regexps in a single string with preg_grep, but it's not right. Instead, preg_grep searches elements of array, which fit one single regexp. So, you just used the wrong function.

Search a letter in a list of words?

I have an array called 'words' storing many words.
For example:
I have 'systematic', 'سلام','gear','synthesis','mysterious', etc.
NB: we have utf8 words too.
How to query efficiently to see which words include letters 's','m','e' (all of them) ?
The output would be:
systematic,mysterious
I have no idea how to do such a thing in PHP. It should be efficient because our server would suffer otherwise.e.
Use a regular expression to split each string into an array of characters, and use array_intersect() to find out if all the characters in your search array is present in the split array:
header('Content-Type: text/plain; charset=utf8');
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$search = array('s','m','e');
foreach ($words as $word) {
$char_array = utf8_str_split($word);
$contains = array_intersect($search, $char_array) == $search;
echo sprintf('%s : %s', $word, (($contains) ? 'True' : 'False'). PHP_EOL);
}
function utf8_str_split($str) {
return preg_split('/(?!^)(?=.)/u', $str);
}
Output:
systematic : True
سلام : False
gear : False
synthesis : False
mysterious : True
Demo.
UPDATE: Or, alternatively, you could use array_filter() with preg_match():
$array = array_filter($words, function($item) {
return preg_match('~(?=[^s]*s)(?=[^m]*m)(?=[^e]*e)~u', $item);
});
Output:
Array
(
[0] => systematic
[4] => mysterious
)
Demo.
This worked to me:
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$letters=array('s','m', 'e');
foreach ($words as $w) {
//print "lets check word $w<br>";
$n=0;
foreach ($letters as $l) {
if (strpos($w, $l)!==false) $n++;
}
if ($n>=3) print "$w<br>";
}
It returns
systematic
mysterious
Explanation
It uses nested foreach: one for the words and the other one for the letters to be matched.
In case any letter is matched, the counter is incremented.
Once the letters loop is over, it checks how many matches were there and prints the word in case it is 3.
Something like this:
$words = array('systematic', 'سلام','gear','synthesis','mysterious');
$result=array();
foreach($words as $word){
if(strpos($word, 's') !== false &&
strpos($word, 'm') !== false &&
strpos($word, 'e') !== false){
$result[] = $word;
}
}
echo implode(',',$result); // will output 'systematic,mysterious'
Your question is wide a little bit.
What I understand from your question that's those words are saved in a database table, so you may filter the words before getting them into the array, using SQL like function.
in case you want to search for a letters in an array of words, you could loop over the array using foreach and each array value should be passed to strpos function.
http://www.php.net/function.strpos
why not use PREG_GREP
$your_array = preg_grep("/[sme]/", $array);
print_r($your_array);
WORKING DEMO

array matching and display in php

i am using PHP scripts to implement this...
$keyword=array('local news','art','local','world','tech','entertainment','news','tech','top stories','in the news','front page','bbc news','week in a glance','week in pictures','top stories');
//$keyword has predefined array of strings
$all_meta_tags=get_meta_tags("http://abcnews.go.com/");
$array=$all_meta_tags['keywords'];//store 'keyword' attribute values in $keyword_meta
Now i have to match contents of $array with $keyword.....the results should give me matched items of $array which are present in $keyword
any help plz...?
can array matching/intersection be done case insensitively??
i mean if
$keyword=array('local news');
$array = 'Local News, International News';
var_dump(array_intersect(preg_split('/,\s*/', $array), $keyword));
then it won't match 'Local News'...can you tel me hw to do it if it is possible??
$inBoth = array_intersect(preg_split('/,\s*/', $array), $keyword);
CodePad.
get_meta_tags() just returns the keywords as a string, so we need to split it into an array. We take into account people adding spaces, newlines or tabs after the ,.
You could also skip the regex, and explode on , and then use array_map('trim', $array).
Without doing this, you run the risk of "art" and " art" not matching.
Update
can array matching be done case insensitively?
If you don't mind the resulting arrays being lowercase, you could use array_map('strtolower', $array) on both arrays before using array_intersect().
Otherwise, this will do it...
$metaKeywords = preg_split('/,\s*/', $array);
$matches = array();
foreach($keyword as $keyword) {
foreach($metaKeywords as $value) {
if (strtolower($value) == strtolower($keyword)) {
$matches[] = $keyword;
}
}
}
$matches will have keywords in both arrays case insensitively.
If you have multibyte strings, use mb_strtolower() or equivalent.
You need to use array_intersect()
http://php.net/manual/en/function.array-intersect.php

Searching within an array of strings

Ok, I'm feeling retarded here,
I have a string like so:
$string = 'function module_testing() {';
or it could be like this:
$string = 'function module_testing()';
or it could be like this:
$string = 'function module_testing($params) {';
or this:
$string = 'function module_testing($params, $another = array())';
and many more ways...
And than I have an array of strings like so:
$string_array = array('module_testing', 'another_function', 'and_another_function');
Now, is there some sort of preg_match that I can do to test if any of the $string_array values are found within the $string string at any given position? So in this situation, there would be a match. Or is there a better way to do this?
I can't use in_array since it's not an exact match, and I'd rather not do a foreach loop on it if I can help it, since it's already in a while loop.
Thanks :)
A foreach loop here is the appropriate solution. Not only is it the most readable but you're looping over three values. The fact that happens within a while loop is a non-issue.
foreach ($string_array as $v) {
if (strpos($string, $v) !== false) {
// found
}
}
You can alternatively use a regular expression:
$search = '\Q' . implode('\E|\Q', $string_array) . '\E';
if (preg_match('!$search!`, $string)) {
// found
}
There are two parts to this. Firstly, there is the | syntax:
a|b|c
which means find a, b or c. The second part is:
\Q...\E
which escapes the contents. This means if your search strings contain any regex special characters (eg () then the regex will still work correctly.
Ultimately though I can't see this being faster than the foreach loop.

Categories