How do I display only match keyword in array - php

This is my array output
Array
(
[0] => Array
(
[tweet_text] => Fedora 16 "Verne" released! http://t.co/lECbdzE0 #Fedora #Linux
)
[1] => Array
(
[tweet_text] => Ubuntu 11.10 "Oneiric Ocelot" released! #Ubuntu #Linux
)
)
Example to find Ubuntu keyword. From the current array how do I filter to show only
Array ( [1] => Array (
[tweet_text] => Ubuntu 11.10 "Oneiric Ocelot" released! #Ubuntu #Linux
)
)
The code
$keywords = array('Ubuntu');
foreach ($keywords as &$keyword) {
$keyword = preg_quote($keyword);
}
$regex = "/(" . implode('|', $keywords) . ")/";
$check = preg_match($regex, $anArray);
if($check == 1) {
// here I want to display only Ubuntu
}
Let me know

preg_grep — Return array entries that match the pattern
example:-
$arr = array('k'=>'ubuntu', 'j'=>'ubuntu1', 'n'=>'fedorra');
$matches = preg_grep('/ubuntu/i', $arr);
if you original source is an multi-dimensional array,
you can try :-
$cmp = array();
foreach ($src as $key=>$arr)
{
$cmp[$key] = $arr['tweet_text'];
}
$matches = preg_grep('/ubuntu/i', $cmp);
// $matches will be an associate array contains the matches
// and $matches and $src are using same index key

There are a few approaches here, basically you could look at your current function: preg_match. By the way i don't think you can put a array into the subject parameter if it requires a string. For now i will guess you are putting a string there with the wrong name.
You could use it also to save the matches found like so:
$check = preg_match($regex, $string, $matches);
print_r($matches);
If it is an array you should approach it like a single result and loop trough it (there are betters ways, but this is an approach you are using and i try to teach you this better.
// Your code ....
foreach($anArray as $rule) {
$check = preg_match($regex, $anArray, $matches);
if($check == 1) {
echo print_r($matches);
}
}

Related

Parse formatted strings containing 3 delimiters to create multiple flat arrays

I have strings in following format:
$strings[1] = cat:others;id:4,9,13
$strings[2] = id:4,9,13;cat:electric-products
$strings[3] = id:4,9,13;cat:foods;
$strings[4] = cat:drinks,foods;
where cat means category and id is identity number of a product.
I want to split these strings and convert into arrays $cats = array('others'); and $ids = array('4','9','13');
I know that it can be done by foreach and explode function through multiple steps. I think I am somewhere near, but the following code does not work.
Also, I wonder if it can be done by preg_match or preg_split in fewer steps. Or any other simpler method.
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach($temps as $temp) {
$tempnest = explode(':', $temp);
$array[$tempnest[0]] .= explode(',', $tempnest[1]);
}
}
My desired result should be:
$cats = ['others', 'electric-products', 'foods', 'drinks';
and
$ids = ['4','9','13'];
One option could be doing a string compare for the first item after explode for cat and id to set the values to the right array.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
$cats = [];
$ids = [];
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = explode(',', $tempnest[1]);
}
if ($tempnest[0] === "id") {
$ids = explode(',', $tempnest[1]);
}
}
print_r($cats);
print_r($ids);
}
Php demo
Output for the first item would for example look like
Array
(
[0] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
If you want to aggregate all the values in 2 arrays, you can array_merge the results, and at the end get the unique values using array_unique.
$strings = ["cat:others;id:4,9,13", "id:4,9,13;cat:electric-products", "id:4,9,13;cat:foods", "cat:drinks,foods"];
$cats = [];
$ids = [];
foreach ($strings as $key=>$string) {
$temps = explode(';', $string);
foreach ($temps as $temp) {
$tempnest = explode(':', $temp);
if ($tempnest[0] === "cat") {
$cats = array_merge(explode(',', $tempnest[1]), $cats);
}
if ($tempnest[0] === "id") {
$ids = array_merge(explode(',', $tempnest[1]), $ids);
}
}
}
print_r(array_unique($cats));
print_r(array_unique($ids));
Output
Array
(
[0] => drinks
[1] => foods
[3] => electric-products
[4] => others
)
Array
(
[0] => 4
[1] => 9
[2] => 13
)
Php demo
I don't generally recommend using variable variables, but you are looking for a sleek snippet which uses regex to avoid multiple explode() calls.
Here is a script that will use no explode() calls and no nested foreach() loops.
You can see how the \G ("continue" metacharacter) allows continuous matches relative the "bucket" label (id or cat) by calling var_export($matches);.
If this were my own code, I'd probably not create separate variables, but a single array containing id and cat --- this would alleviate the need for variable variables.
By using the encountered value as the key for the element to be added to the bucket, you are assured to have no duplicate values in any bucket -- just call array_values() if you want to re-index the bucket elements.
Code: (Demo) (Regex101)
$count = preg_match_all(
'/(?:^|;)(id|cat):|\G(?!^),?([^,;]+)/',
implode(';', $strings),
$matches,
PREG_UNMATCHED_AS_NULL
);
$cat = [];
$id = [];
for ($i = 0; $i < $count; ++$i) {
if ($matches[1][$i] !== null) {
$arrayName = $matches[1][$i];
} else {
${$arrayName}[$matches[2][$i]] = $matches[2][$i];
}
}
var_export(array_values($id));
echo "\n---\n";
var_export(array_values($cat));
All that said, I probably wouldn't rely on regex because it isn't very readable to the novice regex developer. The required logic is much simpler and easier to maintain with nested loops and explosions. Here is my adjustment of your code.
Code: (Demo)
$result = ['id' => [], 'cat' => []];
foreach ($strings as $string) {
foreach (explode(';', $string) as $segment) {
[$key, $values] = explode(':', $segment, 2);
array_push($result[$key], ...explode(',', $values));
}
}
var_export(array_unique($result['id']));
echo "\n---\n";
var_export(array_unique($result['cat']));
P.s. your posted coding attempt was using a combined operator .= (assignment & concatenation) instead of the more appropriate combined operator += (assignment & array union).

PHP How to check if an array contains a pattern from another array

I'm looking for an alternative function that works the same as in_array but which could also check if the search term only contains a part of the given element instead of the whole element:
Currently working with the following script:
$attributes = array('dogs', 'cats', 'fish');
if (in_array($attributes, array('dog','cats','fishess'), true )) {
* does something for cats, but not for dogs and fish
because the function only checks if the given term is identical to the word in the array instead of only a part of the word *
}
How would I build my up function so that it passes words which only contain parts of word in the array aswell?
Preferred example would look something like this:
$words = array('fish', 'sharks');
if (*word or sentence part is* in_array($words, array('fishing', 'sharkskin')){
return 'your result matched 2 elements in the array $words
}
The solution using array_filter and preg_grep functions:
$words = ['fish', 'sharks', 'cats', 'dogs'];
$others = ['fishing', 'sharkskin'];
$matched_words = array_filter($words, function($w) use($others){
return preg_grep("/" . $w . "/", $others);
});
print_r($matched_words);
The output:
Array
(
[0] => fish
[1] => sharks
)
Try the code below:
<?php
$what = ['fish', 'sharks'];
$where = ['fishing', 'sharkskin'];
foreach($what as $one)
foreach($where as $other)
echo (strpos($other, $one)!==false ? "YEP! ".$one." is in ".$other."<br>" : $one." isn't in ".$other."<br>");
?>
Hope it helps =}
Why not just make your own piece of code / function?
foreach ($item in $attributes) {
foreach ($item2 in array('dog','cats','fishess')) {
// Check your custom functionality.
// Do something if needed.
}
}
You can take a look at array_intersect, but it is not going to check pattern matches (which you have somehow mentioned?)
array_intersect() returns an array containing all the values of array1 that are present in all the arguments. Note that keys are preserved.
foreach (array_intersects($attributes, array('dog','cats','fishess') {
// do something.
}
you can use:
array_filter($arr, function($v, $k) {
// do whatever condition you want
return in_array($v, $somearray);
}, ARRAY_FILTER_USE_BOTH);
this function call on every item in the array $arr a function that you can customize, in your case check whether you element in another array or not
I would go with:
$patterns = array('/.*fish.*/', '/.*sharks.*/');
$subjects = array('fishing', 'aaaaa', 'sharkskin');
$matches = array();
preg_replace_callback(
$patterns,
function ($m) {
global $matches;
$matches[] = $m[0];
return $m[0];
},
$subjects
);
print_r($matches); // Array ( [0] => fishing [1] => sharkskin )

Find all substrings within a string with overlap

Hi im trying to find all overlapping substrings in a string here is my code its only finding nonrepeating ACA.
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
echo preg_match_all("/$needle/", $haystack, $matches);
You're using echo to print the return value of preg_match_all. That is, you're displaying only the number of matches found. What you probably wanted to do was something like print_r($matches);, like this:
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
preg_match_all("/$needle/", $haystack, $matches);
print_r($matches);
Output:
Array
(
[0] => Array
(
[0] => ACA
[1] => ACA
[2] => ACA
)
)
Demo
If your real concern is that it counted ACACA only once, well, there are three things that need to be said about that:
That's basically unavoidable with regex.
You really shouldn't count this twice, as it's overlapping. It's not a true recurrence of the pattern.
That said, if you want to count that twice, you could do so with something like this:
echo preg_match_all("/(?=$needle)/", $haystack, $matches);
Output:
4
Demo
Here a script to find all occurences of a substring, also the overlapping ones.
$haystack = "ACAAGACACATGCCACATTGTCC";
$needle = "ACA";
$positions = [];
$needle_len = strlen($needle);
$haystack_len = strlen($haystack);
for ($i = 0; $i <= $haystack_len; $i++) {
if( substr(substr($haystack,$i),0,$needle_len) == $needle){
$positions[]=$i;
}
}
print_r($positions);
Output: Array ( 0, 5, 7, 14 )

Filter a string in PHP

I'm looking to get an array of ID's from the following string.
[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]
Ideally, i'd like to look at this string and get an array of the INT values within images. e.g.
array("3057", "2141", "234");
find images value and explode it to receive array
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
if (preg_match('/images\s*=\s*\"([^\"]+)\"/', $str, $m)) {
$res = explode(',', $m[1]);
print_r($res);
}
Another solution using explode and strpos functions:
$str = '[vc_gallery type="flexslider_fade" interval="3" images="3057,2141,234" onclick="link_image" custom_links_target="_self" img_size="large"]';
foreach (explode(" ", $str) as $v) {
if (strpos($v, "images=") === 0) {
$result = explode(",", explode('"', $v)[1]);
break; // avoids redundant iterations
}
}
print_r($result);
The output:
Array
(
[0] => 3057
[1] => 2141
[2] => 234
)

PHP get array values having a specific word

Consider an array like this,
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
I want to create an array from $sports like this,
$ball = array('Football','cricket ball','tennis ball');
based on the search key(here it is 'ball').
If am looping through the array $sports and checking one by one, will get the result. But then am already inside a loop and that may be even loops more than 50,000 times. So thought of avoiding another loop.
Is there any other way to get this done?
Thanks
Try array_filter() + preg_match() functions:
<?php
header('Content-Type: text/plain; charset=utf-8');
$array = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$word = 'ball';
$results = array_filter(
$array,
function($value) use ($word){
return preg_match('/' . $word . '/i', $value);
}
);
print_r($results);
?>
Shows:
Array
(
[0] => Football
[1] => cricket ball
[2] => tennis ball
)
$sports = array('Football','cricket ball','tennis ball','shuttle bat','hockey stick');
$input = 'ball';
$result = array_filter($sports, function ($item) use ($input) {
if (stripos($item, $input) !== false) {
return $item;
}
});
print_r($result);

Categories