A more forgiving array_intersect in PHP - php

array_intersect takes two arrays and looks for matching === values and returns the result. However the values in the array have to match character for character. Is there a function or a method for comparing two arrays and looking for values that contain similar strings instead of equal similar strings. Something like stripos but with array_intersect.
$array1 = array("howdyhorse", "monkeyjoe", "bill", "donkeymonkey", "carrothorse")
$array2 = array("bill", "horse", "monkeybunk", "apple", "panda")
function($array1, $array2);
Returns an array = array("bill", "horse", "monkeyjoe")
The order is of no particular concern.

Is running all the values of each array through something like
foreach( $array as $slice )
$slice = trim( preg_replace( $pattern, $replacement ) ) ;
to make everything lowercase and remove spaces and special chars and then doing an array_intersect an option?

You could use array_uintersect and similar_text. similar_text is O(N**3), so you need to write your own function if your compare similar logic is simpler.

Related

using str_replace to match whole words /case insensitive [duplicate]

This question already has answers here:
PHP string replace match whole word
(4 answers)
Closed 4 years ago.
I'm trying to replace whole words in a string using str_replace, however, even letters matched in words are being replaced. i tried preg_replace, but couldn't get it to work as i have a big list of words to replace. Any help is appreciated.
$array2 = array('is','of','to','page');
$text = "homepage-of-iso-image";
echo $text1 = str_replace($array2,"",$text);
the output is : home--o-image
For the whole-words issue, there is a solution here using preg_replace(), and your the solution would be to add /\b to the beginning and \b/u to the end of your array-values. The case-insensitive could be handled with preg_replace_callback (see example #1), but if you are working with a small array like your example, I would just recommend duplicating the array-values.
Applied to your example:
$array2 = array(
'/\bis\b/u',
'/\bof\b/u',
'/\bto\b/u',
'/\bpage\b/u',
'/\bIS\b/u',
'/\bOF\b/u',
'/\bTO\b/u',
'/\bPAGE\b/u'
);
$text = "homepage-of-iso-image";
echo $text1 = preg_replace($array2,"",$text);
You could use array_diff
array array_diff ( array $array1 , array $array2 [, array $... ] )
Compares array1 against one or more other arrays and returns the
values in array1 that are not present in any of the other arrays.
<?php
$remove = array('is','of','to','page');
$text = "homepage-of-iso-image";
$parts = explode('-', $text);
$filtered = array_diff($parts, $remove);
print implode('-', $filtered);
Output:
homepage-iso-image

Trim string with array using PHP

How can i trim with array of string in php. If I have an dynamic array as follows :
$arr = array(' ','<?php','?>',"'",'"');
so how can i use this array in trim() to remove those string, I tried very hard in the code below :
$text = trim(trim(trim(trim(trim($text),'<?php'),'?>'),'"'),"'");
but i can not use this because array is dynamic, it may have more than 1000 values.
It takes a lot of time to turn into a loop even after trying it.So I can do anything as follows
$text = trim($text, array(' ','<?php','?>',"'",'"') );
It's possible to apply trim() function to an array. The question seems to be unclear but you can use array_map(). Unclear because there are other enough possible solutions to replace substrings. To just apply trim() function to an array, use the following code.
$array = array(); //Your array
$trimmed_array = array_map('trim', $array); //Your trimmed array is here
If you also want to fulfill the argument requirement in trim() you can apply a custom anonymous function to array_map() like this:
$array = array(); //Your array
$trimmed_array = array_map(function($item){
return trim($item, 'characters to be stripped');
}, $array); //Your trimmed array is here

Array Split In PHP

Now my array is Storing values like
Array([0] => "Aaa", "bbb", "ccc")
How can I make this Array as below using PHP
Array[0] = "Aaa", Array[1] = "bbb"
How to make like this. I tried with explode its not taking values correctly If anyone knows solution. Please help me to get out of this. Thanks in advance.
$oldarray[0]='"abc","def","hij"';
$oldarray[1]='"abc","def","hij"';
$newarray=array();
foreach ($oldarray as $value) {
$newarray[] = str_replace('"','',explode(',',$value));
//print_r($value);die();
}
print_r($newarray);
Use explode
Returns an array of strings, each of which is a substring of string formed by splitting it on boundaries formed by the string delimiter comma.
$array1 = explode(',',$array[0]);
Use str_replace to remove double quotes
str_replace('"', '', $array[0]);
$array1 = explode(',',str_replace('"', '',$array[0]));
Check array1[0], array1[1] and array1[2] to find your values
Use explode to split the value in multiple values based on the coma, use str_replace to remove the quotes :
you do something like this
$newarray = explode(',',str_replace('"', "",$oldarray[]));
or:
$newarray = explode('","',trim($oldarray[],'"'));
docs

using explode function to read a string

My code reads a line from a file, splits the line into elements, and is supposed to put the elements in an array.
I used explode, but it does not put the elements into the array in sequential order.
Example: for input
line: 1000 3000 5000
This is what happens
$a=fgets($file); // $a= 1000 3000 5000
$arr= explode(" ",$a);
$u=$arr[3]; // $u=1000
$w=$arr[6]; // $w=3000
$x=$arr[10]; // $x=5000
This is the desired order:
$u=$arr[0]; // $u=1000
$w=$arr[1]; // $w=3000
$x=$arr[2]; // $x=5000
Why doesn't explode put data sequentially into the array?
It always puts them in sequentially. IF you are seeing this behavior then you must have extra in the document that are being exploded upon resluting in empty array elements. You will either need to pre-process the string or prune empty elements from the array.
Alternatively you could use preg_split with the PREG_SPLIT_NO_EMPTY setting.
Dome examples of that you are trying to do:
// using regex
$arr = preg_split("/ /", $a, PREG_SPLIT_NO_EMPTY);
// pruning the array
$arr = explode(" ", $a);
$arr = array_keys($a, '');
In your example, it's going to put a new array entry per every space.
To get what you're looking for, the returned string would have to be "$u=1000_$w=3000_$x=5000" (underscores represent spaces here)
An alternate way to do this would be to use array_filter to remove the empty elements i.e.
$arr = explode( ' ', $a ); // split string into array
$arr = array_filter( $arr ); // remove empty elements from array
$arr = array_values( $arr ); // strip old array keys giving sequential numbering, i.e. 0,1,2

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

Categories