Echoing matched data from 2 arrays with php - php

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);
}

Related

Compare elements of two arrays php

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);

Search for matching partial values in an array [duplicate]

This question already has answers here:
Filter multidimensional array based on partial match of search value
(3 answers)
startsWith() and endsWith() functions in PHP
(34 answers)
Closed 1 year ago.
$target = 285
$array = array("260-315", "285-317", "240-320")
I need to search the array for the value that begins with the $target value. Also, the $target value will not be limited to 3 digits so I'm searching for a match of the digits before the hyphen.
So I want to end up with
$newTarget = 285-317
$finalTarget = 317
Note: I'm only searching for a match of the digits before the hyphen so "200-285" would not be a match
What you asked me in comment(below my answer),for that you can do it like below (My changed answer):-
<?php
$target = 285;
$array = array('260-315', '285-317', '240-320',"200-285");
foreach($array as $key=>$value){
if($target ==explode('-',$value)[0]){
echo $newTarget = $array[$key];
echo PHP_EOL;
echo $finalTarget = explode('-',$array[$key])[1];
}
}
?>
https://eval.in/702862
I can help you filter your array down to members that start with your target.
You can then split the return values to get to your final target.
<?php
$target = '285';
$array = array('260-315', '285-317', '240-320');
$out = array_filter($array, function($val) use ($target) {
return strpos($val, $target) === 0;
});
var_export($out);
Output:
array (
1 => '285-317',
)
<?php
$target = 285;
$arrStack = array(
"260-315",
"285-317",
"240-320",
);
$result = preg_grep('/'.$target.'/',$arrStack);
echo "<pre>"; print_r($result); echo "</pre>";
Something like this could work for you ? array_filter
$target = 285;
$array = array("260-315", "285-317", "240-320");
$newTarget = null;
$finalTarget = null;
$filteredArray = array_filter($array, function($val) use ($target) {
return strpos($val, $target."-") === 0;
});
if(isset($filteredArray[0])){
$newTarget = $filteredArray[0];
$finalTarget = explode($filteredArray[0], "-")[1];
}
Instead of finding what matches, you could exclude what doesn't match with array_filter.
For example:
$target = 285;
$original = array('260-315', '285-317', '240-320');
$final = array_filter($original, function ($value) use ($target) {
// Check if match starts at first character. Have to use absolute check
// because no match returns false
if (stripos($value, $target) === 0) {
return true;
}
return false;
});
The $final array will be a copy of the $original array without the non-matching values.
To output the first digits, you can then loop through your array of matches and get the value before the hyphen:
foreach ($final as $match) {
$parts = explode('-', $match);
if (is_array($parts) && ! empty($parts[0])) {
// Show or do something with value
echo $parts[0];
}
}
Use array_filter:
Example:
$target = '260';
$array = ['260-315', '285-317', '240-320'];
$matches = array_filter($array, function($var) use ($target) { return $target === explode('-', $var)[0]; });
print_r($matches);
Output:
Array
(
[0] => 260-315
)

Check if string contains word in array [duplicate]

This question already has answers here:
String contains any items in an array (case insensitive)
(15 answers)
Closed 2 years ago.
This is for a chat page. I have a $string = "This dude is a mothertrucker". I have an array of badwords: $bads = array('truck', 'shot', etc). How could I check to see if $string contains any of the words in $bad?
So far I have:
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
// YES! }
}
Except when I do this, when a user types in a word in the $bads list, the output is NO! followed by YES! so for some reason the code is running it twice through.
function contains($str, array $arr)
{
foreach($arr as $a) {
if (stripos($str,$a) !== false) return true;
}
return false;
}
1) The simplest way:
if ( in_array( 'three', ['one', 'three', 'seven'] ))
...
2) Another way (while checking arrays towards another arrays):
$keywords=array('one','two','three');
$targets=array('eleven','six','two');
foreach ( $targets as $string )
{
foreach ( $keywords as $keyword )
{
if ( strpos( $string, $keyword ) !== FALSE )
{ echo "The word appeared !!" }
}
}
can you please try this instead of your code
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot');
foreach($bads as $bad) {
$place = strpos($string, $bad);
if (!empty($place)) {
echo 'Bad word';
exit;
} else {
echo "Good";
}
}
There is a very short php script that you can use to identify bad words in a string which uses str_ireplace as follows:
$string = "This dude is a mean mothertrucker";
$badwords = array('truck', 'shot', 'ass');
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
if ($banstring) {
echo 'Bad words found';
} else {
echo 'No bad words in the string';
}
The single line:
$banstring = ($string != str_ireplace($badwords,"XX",$string))? true: false;
does all the work.
You can flip your bad word array and do the same checking much faster. Define each bad word as a key of the array. For example,
//define global variable that is available to too part of php script
//you don't want to redefine the array each time you call the function
//as a work around you may write a class if you don't want global variable
$GLOBALS['bad_words']= array('truck' => true, 'shot' => true);
function containsBadWord($str){
//get rid of extra white spaces at the end and beginning of the string
$str= trim($str);
//replace multiple white spaces next to each other with single space.
//So we don't have problem when we use explode on the string(we dont want empty elements in the array)
$str= preg_replace('/\s+/', ' ', $str);
$word_list= explode(" ", $str);
foreach($word_list as $word){
if( isset($GLOBALS['bad_words'][$word]) ){
return true;
}
}
return false;
}
$string = "This dude is a mothertrucker";
if ( !containsBadWord($string) ){
//doesn't contain bad word
}
else{
//contains bad word
}
In this code we are just checking if an index exist rather than comparing bad word with all the words in the bad word list.
isset is much faster than in_array and marginally faster than array_key_exists.
Make sure none of the values in bad word array are set to null.
isset will return false if the array index is set to null.
Put and exit or die once it find any bad words, like this
foreach ($bads as $bad) {
if (strpos($string,$bad) !== false) {
//say NO!
}
else {
echo YES;
die(); or exit;
}
}
You can do the filter this way also
$string = "This dude is a mothertrucker";
if (preg_match_all('#\b(truck|shot|etc)\b#', $string )) //add all bad words here.
{
echo "There is a bad word in the string";
}
else {
echo "There is no bad word in the string";
}
Wanted this?
$string = "This dude is a mothertrucker";
$bads = array('truck', 'shot', 'mothertrucker');
foreach ($bads as $bad) {
if (strstr($string,$bad) !== false) {
echo 'NO<br>';
}
else {
echo 'YES<br>';
}
}
If you want to do with array_intersect(), then use below code :
function checkString(array $arr, $str) {
$str = preg_replace( array('/[^ \w]+/', '/\s+/'), ' ', strtolower($str) ); // Remove Special Characters and extra spaces -or- convert to LowerCase
$matchedString = array_intersect( explode(' ', $str), $arr);
if ( count($matchedString) > 0 ) {
return true;
}
return false;
}
I would go that way if chat string is not that long.
$badwords = array('mothertrucker', 'ash', 'whole');
$chatstr = 'This dude is a mothertrucker';
$chatstrArr = explode(' ',$chatstr);
$badwordfound = false;
foreach ($chatstrArr as $k => $v) {
if (in_array($v,$badwords)) {$badwordfound = true; break;}
foreach($badwords as $kb => $vb) {
if (strstr($v, $kb)) $badwordfound = true;
break;
}
}
if ($badwordfound) { echo 'You\'re nasty!';}
else echo 'GoodGuy!';
$string = "This dude is a good man";
$bad = array('truck','shot','etc');
$flag='0';
foreach($bad as $word){
if(in_array($word,$string))
{
$flag=1;
}
}
if($flag==1)
echo "Exist";
else
echo "Not Exist";

Filter a set of bad words out of a PHP array

I have a PHP array of about 20,000 names, I need to filter through it and remove any name that has the word job, freelance, or project in the name.
Below is what I have started so far, it will cycle through the array and add the cleaned item to build a new clean array. I need help matching the "bad" words though. Please help if you can
$data1 = array('Phillyfreelance' , 'PhillyWebJobs', 'web2project', 'cleanname');
// freelance
// job
// project
$cleanArray = array();
foreach ($data1 as $name) {
# if a term is matched, we remove it from our array
if(preg_match('~\b(freelance|job|project)\b~i',$name)){
echo 'word removed';
}else{
$cleanArray[] = $name;
}
}
Right now it matches a word so if "freelance" is a name in the array it removes that item but if it is something like ImaFreelaner then it does not, I need to remove anything that has the matching words in it at all
A regular expression is not really necessary here — it'd likely be faster to use a few stripos calls. (Performance matters on this level because the search occurs for each of the 20,000 names.)
With array_filter, which only keeps elements in the array for which the callback returns true:
$data1 = array_filter($data1, function($el) {
return stripos($el, 'job') === FALSE
&& stripos($el, 'freelance') === FALSE
&& stripos($el, 'project') === FALSE;
});
Here's a more extensible / maintainable version, where the list of bad words can be loaded from an array rather than having to be explicitly denoted in the code:
$data1 = array_filter($data1, function($el) {
$bad_words = array('job', 'freelance', 'project');
$word_okay = true;
foreach ( $bad_words as $bad_word ) {
if ( stripos($el, $bad_word) !== FALSE ) {
$word_okay = false;
break;
}
}
return $word_okay;
});
I'd be inclined to use the array_filter function and change the regex to not match on word boundaries
$data1 = array('Phillyfreelance' , 'PhillyWebJobs', 'web2project', 'cleanname');
$cleanArray = array_filter($data1, function($w) {
return !preg_match('~(freelance|project|job)~i', $w);
});
Use of the preg_match() function and some regular expressions should do the trick; this is what I came up with and it worked fine on my end:
<?php
$data1=array('JoomlaFreelance','PhillyWebJobs','web2project','cleanname');
$cleanArray=array();
$badWords='/(job|freelance|project)/i';
foreach($data1 as $name) {
if(!preg_match($badWords,$name)) {
$cleanArray[]=$name;
}
}
echo(implode($cleanArray,','));
?>
Which returned:
cleanname
Personally, I would do something like this:
$badWords = ['job', 'freelance', 'project'];
$names = ['JoomlaFreelance', 'PhillyWebJobs', 'web2project', 'cleanname'];
// Escape characters with special meaning in regular expressions.
$quotedBadWords = array_map(function($word) {
return preg_quote($word, '/');
}, $badWords);
// Create the regular expression.
$badWordsRegex = implode('|', $quotedBadWords);
// Filter out any names that match the bad words.
$cleanNames = array_filter($names, function($name) use ($badWordsRegex) {
return preg_match('/' . $badWordsRegex . '/i', $name) === FALSE;
});
This should be what you want:
if (!preg_match('/(freelance|job|project)/i', $name)) {
$cleanArray[] = $name;
}

php -> delete items from array which contain words from a blacklist

I have got an array with several twitter tweets and want to delete all tweets in this array which contain one of the following words blacklist|blackwords|somemore
who could help me with this case?
Here's a suggestion:
<?php
$banned_words = 'blacklist|blackwords|somemore';
$tweets = array( 'A normal tweet', 'This tweet uses blackwords' );
$blacklist = explode( '|', $banned_words );
// Check each tweet
foreach ( $tweets as $key => $text )
{
// Search the tweet for each banned word
foreach ( $blacklist as $badword )
{
if ( stristr( $text, $badword ) )
{
// Remove the offending tweet from the array
unset( $tweets[$key] );
}
}
}
?>
You can use array_filter() function:
$badwords = ... // initialize badwords array here
function filter($text)
{
global $badwords;
foreach ($badwords as $word) {
return strpos($text, $word) === false;
}
}
$result = array_filter($tweetsArray, "filter");
use array_filter
Check this sample
$tweets = array();
function safe($tweet) {
$badwords = array('foo', 'bar');
foreach ($badwords as $word) {
if (strpos($tweet, $word) !== false) {
// Baaaad
return false;
}
}
// OK
return true;
}
$safe_tweets = array_filter($tweets, 'safe'));
You can do it in a lot of ways, so without more information, I can give this really starting code:
$a = Array(" fafsblacklist hello hello", "white goodbye", "howdy?!!");
$clean = Array();
$blacklist = '/(blacklist|blackwords|somemore)/';
foreach($a as $i) {
if(!preg_match($blacklist, $i)) {
$clean[] = $i;
}
}
var_dump($clean);
Using regular expressions:
preg_grep($array,"/blacklist|blackwords|somemore/",PREG_GREP_INVERT)
But i warn you that this may be inneficient and you must take care of punctuation characters in the blacklist.

Categories