So I have two arrays:
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
I need to compare elements of input phrases array with bad words array and output new array with phrases WITHOUT bad words like this:
$outputarray = array('nothing-bad-here', 'more-clean-stuff','one-more-clean', 'clean-clean');
I tried doing this with two foreach loops but it gives me opposite result, aka it outputs phrases WITH bad words.
Here is code I tried that outputs opposite result:
function letsCompare($inputphrases, $badwords)
{
foreach ($inputphrases as $inputphrase) {
foreach ($badwords as $badword) {
if (strpos(strtolower(str_replace('-', '', $inputphrase)), strtolower(str_replace('-', '', $badword))) !== false) {
$result[] = ($inputphrase);
}
}
}
return $result;
}
$result = letsCompare($inputphrases, $badwords);
print_r($result);
this is not a clean solution, but hope, you'll got what is going on. do not hesitate to ask for clearence. repl.it link
$inputphrases = array('this-is-sentence-with-bad-word', 'nothing-bad-here', 'more-clean-stuff', 'this-is-nasty', 'this-contains-some-racist-term', 'one-more-clean', 'clean-clean', 'contains-bad-language');
$new_arr = array_filter($inputphrases, function($phrase) {
$badwords = array('bad-word', 'some-racist-term', 'nasty', 'bad-language');
$c = count($badwords);
for($i=0; $i<$c; $i++) {
if(strpos($phrase, $badwords[$i]) !== false){
return false;
}
}
return true;
});
print_r($new_arr);
Related
I have an array which contains bunch of strings, and I would like to find all of the possible combinations no matter how it's being sorted that match with given string/word.
$dictionary = ['flow', 'stack', 'stackover', 'over', 'code'];
input: stackoverflow
output:
#1 -> ['stack', 'over', 'flow']
#2 -> ['stackover', 'flow']
What I've tried is, I need to exclude the array's element which doesn't contain in an input string, then tried to match every single merged element with it but I'm not sure and get stuck with this. Can anyone help me to figure the way out of this? thank you in advance, here are my code so far
<?php
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$word = 'stackoverflow';
$dictHas = [];
foreach ($dict as $w) {
if (strpos($word, $w) !== false) {
$dictHas[] = $w;
}
}
$result = [];
foreach ($dictHas as $el) {
foreach ($dictHas as $wo) {
$merge = $el . $wo;
if ($merge == $word) {
} elseif ((strpos($word, $merge) !== false) {
}
}
}
print_r($result);
For problems like this you want to use backtracking
function splitString($string, $dict)
{
$result = [];
//if the string is already empty return empty array
if (empty($string)) {
return $result;
}
foreach ($dict as $idx => $term) {
if (strpos($string, $term) === 0) {
//if the term is at the start of string
//get the rest of string
$substr = substr($string, strlen($term));
//if all of string has been processed return only current term
if (empty($substr)) {
return [[$term]];
}
//get the dictionary without used term
$subDict = $dict;
unset($subDict[$idx]);
//get results of splitting the rest of string
$sub = splitString($substr, $subDict);
//merge them with current term
if (!empty($sub)) {
foreach ($sub as $subResult) {
$result[] = array_merge([$term], $subResult);
}
}
}
}
return $result;
}
$input = "stackoverflow";
$dict = ['flow', 'stack', 'stackover', 'over', 'code'];
$output = splitString($input, $dict);
I am trying to compare the contents of 2 arrays
<?php
$badwords = array('badword1','badword2','badword3');
$domains = array('domainword1.com', 'word2domain.com', 'domain.com');
if (preg_match($badwords,$domains) { // searched and did not find if it works like this
- echo the $domains that matches the $badwords // this is what i don't know how to do
}
It should echo in this case:
Matched domains are:
domainword1.com
word2domain.com
in new rows.
How am i suppose to do this?
I really don't know why you need regex in this case. Secondly, as Jim mentioned What counts as a match in this case? Well that's the thing.
You need to rewrite your $badwords array from
$badwords = array('badword1','badword2','badword3');
to
$badwords = array('word1','word2','word3');
Using the below code you get the desired output.
<?php
$badwords = array('word1','word2','word3');
$domains = array('domainword1.com', 'word2domain.com', 'domain.com');
$newarr = array();
foreach($badwords as $k=>$v)
{
foreach($domains as $k1=>$v1)
{
if(strpos($v1,$v)!==false)
{
array_push($newarr,$v1);
}
}
}
print_r($newarr);
OUTPUT:
Array
(
[0] => domainword1.com
[1] => word2domain.com
)
You can't use preg_match like this if you need to match any of $badwords to any of $domains.
Instead you should do something like this:
<?php
$badwords = array('badword1', 'badword2', 'badword3', 'badword(\d+)');
$domains = array('domainword1.com', 'word2domain.com', 'domain.com', 'badword1.com', 'ohbadword123.com');
$badDomains = array_filter($domains, function($domain) use ($badwords) {
$found = false;
foreach ($badwords as $badword) {
// use this if you dont' need regular expressions:
// if (substr_count($domain, $badword)>0) {
// use this if you need them:
if (preg_match('/' . $badword . '/', $domain)) {
$found = true;
break;
}
}
return $found;
});
if (!empty($badDomains)) {
echo "Domains with bad words:\n - " . join("\n - ", $badDomains);
}
I have two arrays, one with a large set of URL paths and another with search IDs. Each of the URL paths has one unique ID in common. By the search ID we need to find the longest URL with the unique ID. Here is my code, I will explain a bit more later.
<?php
function searchstring($search, $array) {
foreach($array as $key => $value) {
if (stristr($value, $search)) {
echo $value;
}
}
return false;
}
$array = array(
"D:\winwamp\www\info\961507\Good_Luck_Charlie",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3",
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3\The_Curious_Case_of_Mr._Dabney",
"D:\winwamp\www\info\961506\Good_Luck_Charl",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1",
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1\Study_Date");
$searchValues = array("961507","961506");
foreach($searchValues as $searchValue) {
$result = searchstring($searchValue, $array);
}
?>
This gives the value of all matched IDs. Now if you see my array there are four sets of URL paths. What I want is that if I search with "961507" it should give:
"D:\winwamp\www\info\961507\Good_Luck_Charlie\season_1\episode_3\The_Curious_Case_of_Mr._Dabney"
If i search with "961506", it should give:
"D:\winwamp\www\info\961506\Good_Luck_Charlie\season_1\episode_1\Study_Date"
Now what I am getting are all the arrays that matched with my searched ID. Can you please help me to find out how can I accomplish this? Because I have more than 98000 URLs to sort out.
Change the function as
function searchstring($search, $array) {
$length = 0;
$result = "";
foreach($array as $key => $value) {
if (stristr($value, $search)) {
if($length < strlen($value)) {
$length = strlen($value);
$result = $value;
}
}
}
return $result;
}
To print value use:
foreach($searchValues as $searchValue) {
$result = searchstring($searchValue, $array);
echo $result;
}
Or
$result = array();
foreach($searchValues as $searchValue) {
$result[] = searchstring($searchValue, $array);
}
print_r($result);
How can I determine if one array is a subset of another (all elements in the first are present in the second)?
$s1 = "string1>string2>string3>string4>string5>string6>";
$arr1 = explode(">", $s1);
$s2 = "string1>string4>string5";
$arr2 = explode(">", $s2);
$isSubset = /* ??? */
if (array_intersect($array1, $array2) == $array1) {
// $array1 is a subset of $array2
}
Simple: use array subtraction.
On array subtraction, you will know whether or not one array is a subset of the other.
Example:
if (!array_diff($array1, $array2)) {
// $array1 is a subset of $array2
}
Reference: array_diff
You can use array_intersect also.
Try that
If you start from strings, you could check strstr($fullString,$subsetStr);. But that'll only work when all chars have the same order: 'abcd','cd' will work, but 'abcd','ad' won't.
But instead of writing your own, custom, function you should know that PHP has TONS of array functions, so its neigh on impossible that there isn't a std function that can do what you need it to do. In this case, I'd suggest array_diff:
$srcString = explode('>','string1>string2>string3>string4>string5');
$subset = explode('>','string3>string2>string5');
$isSubset = array_diff($subset,$srcString);
//if (empty($isSubset)) --> cf comments: somewhat safer branch:
if (!$isSubset)
{
echo 'Subset';
return true;
}
else
{
echo 'Nope, substrings: '.implode(', ',$isSubset).' Didn\'t match';
return false;
}
I would create an associated array of the larger array, then iterate through the smaller array, looking for a non collision, if you find one, return false.
function isSubset($arr1,$arr2){
$map = Array();
for ($i=0;$i<count($arr1);$i++){
$map[$arr[$i]]=true;
}
for ($i=0;$i<count($arr2);$i++){
if (!isset($map[$arr2[$i]])){
return false;
}
}
return true;
$s1 = "1>2>3>4>5>6>7";
$arr1 = explode(">",$s1);
$s2 = "1>2>3";
$arr2 = explode(">",$s2);
if(isSub($arr1,$arr2)){
echo 'true';
}else{
echo 'false';
}
function isSub($a1,$a2){
$num2 = count($a2);
$sub = $num2;
for($i = 0;$i < $num2 ;$i++){
if(in_array($a2[$i],$a1)){
$sub--;
}
}
return ($sub==0)? true:false;
}
Simple function which will return true if array is exact subset otherwise false. Solution is applicable for two dimensional array as well.
function is_array_subset($superArr, $subArr) {
foreach ($subArr as $key => $value) {
//check if keys not set in super array OR values are unequal in both array.
if (!isset($superArr[$key]) || $superArr[$key] != $value) {
return false;
}
}
return true;
}
I want to make a PHP script that takes a PHP GET variable $_GET[q] made up of many different words or terms and checks to see if it contains any "keywords" that are stored in an array. An example of this would be It could look like "What time is it in San Francisco". I would want the script to pick up on "time" and "san francisco" as an example. I have played about with using
if(stripos($_GET[q],'keyword1','keyword2'))
but haven't had much luck.
Does anyone know how I could do this?
I hope everyone can understand what I am trying to describe.
You can make an array of keywords, then loop though until you find a match.
$array = array('keyword1', 'keyword2');
$found = false;
foreach($array as $x){
if(stripos($_GET['q'], $x) !== false){
$found = true;
break;
}
}
if($found){
}
UPDATE: If you want to match ALL keywords, you can do this instead:
$array = array('keyword1', 'keyword2');
$found = true;
foreach($array as $x){
$found &= stripos($_GET['q'], $x) !== false;
}
if($found){
}
DEMO: http://codepad.org/LaEX6m67
UPDATE 2: Because I'm crazy and like one-liners, you can do this in PHP 5.3+:
$array = array('keyword1', 'keyword2');
$val = $_GET['q'];
$found = array_reduce($array, function($x, $v) use($val){
return $x && stripos($val, $v) !== false;
}, true);
if($found){
}
DEMO: http://codepad.viper-7.com/Y48sHR
foreach($arr as $value){
if(stripos($_GET[q],$value){
do stuff
}
}
Use in_array function:
// assuming $arr is your array of keywords
if (in_array($_GET['q'], $arr))
echo "found a match\n";
EDIT: Based on your comments here is the code you can use, that works without any loop:
$arr = array('keyword1', 'keyword2', 'keyword3');
$brr = array_map(create_function('$m', 'return "/\b" . $m . "\b/";'), $arr);
if ($_GET['q'] !== preg_replace($brr, '', $_GET['q']))
echo "found a match\n";
else
echo "didn't find a match\n";