im trying to search in an array for badwords.
my array looks like:
Array
(
[base] => 2312783821823912
[charset] => utf-8
[Product] => Samsung PD291 Printer
[meta] => Array
(
[description] => fucking nice Printer
[keywords] =>
)
[n2] => Array
(
[w1] => Array
(
[0] => printer
)
[w2] => Array
(
[0] => Menu
[1] => Main menu
[2] => Social
[3] => Speakers
[4] => 2015
[5] => Highlight
[6] => And... Action!
[7] => Short
[8] => Platin
[9] => Gold
[10] => Silber
[11] => Bronze
[12] => partner
)
)
}
I have an badword array like: $bad = array("fuck", "....);
Now im little bit confused what would be the fastest way to scan all values of the first array and return true or false if it contains badwords?
any advice would help ;-)
Thanks!
//edit:
Thanks # everybody...
I will use:
class BadWordFilter {
private static $bad = "/fuck|ass/i";
public static function hasBadWords($input) {
foreach ($input as $element) {
if (is_array($element)) {
if (self::hasBadWords($element)) {
return true;
}
} else {
if (preg_match(self::$bad, $element)) {
return true;
}
}
}
return false;
}
}
I have tested it, and it will be the fastest solutions for my problem ;-))
Thanks everybody
I think the fastest way is to json_encode the array and scan the json string for the bad words.
Not tested but something like this should work:
function badWordsExists($input_array, $blacklist){
$jsonstring = json_encode($input_array);
foreach($blacklist as $string) {
if(strpos($jsonstring, $string) !== false) {
return true;
}
}
return false;
}
Using regex should be faster but this is just an example to give you a idea how it may work.
You can do it with a recursive search which ends its task when a bad word is found. Note, that converting it to json is sub-optimal, since you convert it into a string and then try to find the bad words in the string. It is time-consuming, especially if you have many arrays to check for bad words.
public class BadWordFilter {
private static $bad = array(); //use your array instead
public static function hasBadWords($input) {
foreach ($element in $input) {
if (is_array($element)) {
if (self::hasBadWords($element)) {
return true;
}
} else {
foreach ($bad as $badWord) {
if(strpos($element, $badWord) !== false) {
return true;
}
}
}
}
return false;
}
}
A recursive function is the answer here. The below code will detect any string in at any element of a given array.
<?php
function containsWord($haystack, $badWord)
{
foreach ($haystack as $index => $item) {
if (is_array($item)) {
containsWord($item, $badWord);
} else {
if (strpos($item, $badWord) !== false) {
echo "'$badWord' has been detected in '$item' at index '$index'";
return true;
}
}
}
echo "$badWord is not in the array";
return false;
}
$array = [1 => [4=> 'badword', 5=> 'qw'], 2 => 'b', 3 => 'c'];
containsWord($array, 'bad');
The output of the above code will be:
'bad' has been detected in 'badword' at index '4'
Hope this helps :)
Related
This question already has answers here:
How to use return inside a recursive function in PHP
(4 answers)
Closed 3 years ago.
I need to return a value from a multidimensional array based on key.
Basically i don't want to create 2 or 3 for loops, because the array can be nested like endless.
Example of my array
$menu = Array
(
[16] => Array
(
[categories_id] => 16
[categories_name] => Recorders
[parent_name] => Recorders
[children] => Array
(
[23] => Array
(
[categories_id] => 23
[categories_name] => Security
[parent_name] => Recorders - Security
[children] => Array
(
[109] => Array
(
[categories_id] => 109
[categories_name] => 4CH NVR
[parent_name] => Recorders - Security - 4CH NVR
)
[110] => Array
(
[categories_id] => 110
[categories_name] => 8CH NVR
[parent_name] => Recorders - Security - 8CH NVR
)
I found another solution which almost works:
function findParentNameFromCategory($obj, $search)
{
if (!is_array($obj) && !$obj instanceof Traversable) return;
foreach ($obj as $key => $value) {
if ($key == $search) {
return $value['parent_name'];
} else {
return findParentNameFromCategory($value, $search);
}
}
}
The problem with this is that it just echo the value. I need to assign the value to a var. If i changed echo to return i didn't get any value back at all.
$test = findParentNameFromCategory($menu, 109);
when i echo $test i don't have any value at all
array_walk_recursive($obj, function(&$v, $k){
if($k == $search)
return $v['parent_name'];
});
in your fix you forgot about the else case. so you should return the value of recursive call also:
function findParentNameFromCategory($obj, $search)
{
if (!is_array($obj) && !$obj instanceof Traversable) return;
foreach ($obj as $key => $value) {
if ($key == $search) {
$return = $value['parent_name'];
} else {
$return = findParentNameFromCategory($value, $search);
}
if ($return !== null) {
return $return;
}
}
}
I have the following array:
Array
(
[0] => Array
(
[CODE] => OK
[company_id] => 170647449000
[taxnumber] => 944703420
[name] => SOME NAME
[title] => S.A
)
[1] => Array
(
[CODE] => OK
[company_id] => 17063649000
[taxnumber] => 999033420
[name] => SOME OTHER NAME
[title] => ANOTHER DIFFERENT TITLE
)
)
If the array contain the company_id with the value 17063649000 I need to extract that array (1) in an new array, so I can manipulate it further.
I make numerous code snippets but I am not even close to the solution. I still can not figure out how can I find if the $value (17063649000) exists in the array....not to mention how to extract that specific array (1) from the existing array....
My latest attempt was to modify this and to make it to work, but I am still not managing to make it:
function myfunction($agents, $field, $value)
{
foreach($agents as $key => $agent)
{
if ( $agent[$field] === $value )
return $key;
}
return false;
}
I always get false, even I am sending the value that exists.
Replace return $key with return $agent and operator === with ==.
=== checks type too, it could be reason why it doesn't work.
if your array is $companies then
function getCompany($search_id, $companies) {
foreach($company in $companies) {
if ($companies['company_id'] == $search_id) {
return $company;
}
}
return false;
}
$companies = [...];
$search = 17063649000;
if ($company = getCompany($search, $companies) ) {
// do something with $company
} else {
// not found
}
I'm trying to read recursively into an array until I'm getting a string. Then I try to explode it and return the newly created array. However, for some reason it does not assign the array:
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
foreach($arr as & $a)
$a = go_in($a);
else
return explode("\n", $arr);
}
EDIT:
Here's the array definition as printed by print_r:
Array
(
[products] => Array
(
[name] => Arduino Nano Version 3.0 mit ATMEGA328P
[id] => 10005
)
[listings] => Array
(
[category] =>
[title] => This is the first line
This is the second line
[subtitle] => This is the first subtitle
This is the second subtitle
[price] => 24.95
[quantity] =>
[stock] =>
[shipping_method] => Slow and cheap
[condition] => New
[defects] =>
)
[table_count] => 2
[tables] => Array
(
[0] => products
[1] => listings
)
)
I'd use this:
array_walk_recursive($array,function(&$value,$key){
$value = explode("\n",$value);
});
However, this fixes your function:
function &go_in(&$arr) { // $arr is a multi-dimensional array
if (is_array($arr)){
foreach($arr as & $a) $a = go_in($a);
} else {
$arr = explode("\n", $arr);
}
return $arr;
}
When writing nested conditions/loops - always add braces for better readability and to prevent bugs.. Also you should return the go_in function, because it is recursive, it needs to be passed to the calling function instance.
function go_in($arr) { // $arr is a multi-dimensional array
if (is_array($arr))
{
foreach($arr as &$a)
{
return go_in($a);
}
}
else
{
return ($arr);
}
}
The original array was not returned in the function:
function go_in($arr) {
if (is_array($arr))
foreach($arr as &$a)
$a = go_in($a);
else
if (strpos($arr, "\n") !== false)
return explode("\n", $arr);
return $arr;
}
EDIT:
Now, it only really edits the strings that contain a linebreak. Before it would edit every string which meant that every string was returned as an array.
I have this array:
Array
(
[0] => CMS_ADMIN
[1] => CMS_ACADEMIC
[2] => CMS_FINANCE
[3] => HRM_HR
[4] => SRM_D
[5] => SRM_CNC
[6] => SRM_TM
[7] => SRM_DE
)
I would like to get the array by searching to the array value using the word provided. Let say I'm just provide the 'CMS' word, so how i'm gonna get the [0] => CMS_ADMIN, [1] =>CMS_ACADEMIC, [2] => CMS_FINANCE assign to the new array. Please help....
With a function that looks like this:
function array_filter_prefix($array, $prefix) {
$result = array();
foreach ($array as $value) {
if (strpos($value, $prefix) === 0) {
$result[] = $value;
}
}
return $result;
}
Given an input array, $test, you can then do this to get the result:
$result = array_filter_prefix($test, 'CMS');
print_r($result);
Codepad here.
batter style in PHP 5.3
$prefix = "CMS";
$new = array_filter($array, function ($str) use ($prefix) {
return (strpos($str, $prefix) === 0);
});
I'm working on a menu system and am working on some complex issues. The menu is generated from a array. This array is included in a pastebin because it's really big. I want to search in the array and get the hierarchical path of the value I'm searching while also getting the values next to the parents you run trough. As I said its quite complex.
In the pastebin is the array and the result I want to function to return:
-->pastebin<--
I tried writing this function quite a few times but always get stuck in the middle.
Here is a function:
function get_item_recursive($id, $menu_array = array())
{
foreach($menu_array as $menu_item)
{
if(isset($menu_item['id']) && $menu_item['id'] == $id)
{
$menu_item['subitems'] = array();
return $menu_item;
}
else
{
if(isset($menu_item['subitems']) && !empty($menu_item['subitems']))
{
$found = get_item_recursive($id, $menu_item['subitems']);
if($found)
{
return $menu_item;
}
}
}
}
return FALSE;
}
I have not tested it, but this is the idea.
You are basically looking for the path to build something like a breadcrumb? You can use a recursive function for that:
function findPath($haystack, $id, $parents = array()) {
foreach ($haystack as $k => $v) {
if ($v['id'] == $id) {
return array_merge($parents, array($v));
} else if (!empty($v['subitems'])) {
unset($v['subitems']);
$return = findPath(
$haystack[$k]['subitems'],
$id,
array_merge($parents, array($v))
);
if ($return) return $return;
}
}
return false;
}
Executing this function like this:
findPath($haystack, 11);
Would return:
Array (
[in-balans] => Array
(
[id] => 2
[slug] => in-balans
[title] => In balans
)
[arbodienstverlening] => Array
(
[id] => 10
[slug] => arbodienstverlening
[title] => Arbodienstverlening
)
[arbo] => Array
(
[id] => 11
[slug] => arbo
[title] => Arbo
[subitems] =>
)
)