The nature of the situation, I need 1 pattern to do the following:
Create pattern that should find
exact match for single words
an exact match for a combination of 2 words.
a match of 2 words that could be found in a string.
My issue is with #3. Currently I have:
$pattern = '/\s*(foo|bar|blah|some+text|more+texted)\s*/';
How can I append to this pattern that will find "bad text" in any combination in a string.
Any ideas?
To check string for word bad use regex
/\bbad\b/
To check string for phrase bad text use regex
/\bbad text\b/
To check string for any combination of words bad and text use regex
/\b(bad|text)\s+(?!\1)(?:bad|text)\b/
To check string for presence of words bad and text use regex
/(?=.*\bbad\b)(?=.*\btext\b)/
Couple ways to do this, but here's an easy one
$array_needles = array("needle1", "needle2", etc...);
$array_found_needles = array();
$haystack = "haystack";
foreach ($array as $key=>$val) {
if(stristr($haystack, $val) {
//do whatever you want if its found
$array_found_needles[] = $val; //save the value found
}
}
$found = count($array_found_needles);
if ($found == 0) {
//do something with no needles found
} else if($found == 1) {
//do something with 1 needle found
} else if($found == 2) {
//do something with two needles found, etc
}
Related
I wrote a short function that should check if user input does contain any bad words that I predefined inside $bad_words array. I don't even care to replace them - I just want to ban if there are any. The code seems to work as it should - in the example below will detect the quoted string badword and the function does return true.
My question: Is this a good way to use foreach and strpos()? Perhaps there is better way to check if $input contains one of the $bad_words array elements? Or is it just fine as I wrote it?
function checkswearing($input)
{
$input = preg_replace('/[^0-9^A-Z^a-z^-^ ]/', '', $input);//clean, temporary $input that just contains pure text and numbers
$bad_words = array('badword', 'reallybadword', 'some other bad words');//bad words array
foreach($bad_words as $bad_word)
{//so here I'm using a foreach loop with strpos() to check if $input contains one of the bad words or not
if (strpos($input, $bad_word) !== false)
return true;//if there is one - no reason to check further bad words
}
return false;//$input is clean!
}
$input = 'some input text, might contain a "badword" and I\'d like to check if it does or not';
if (checkswearing($input))
echo 'Oh dear, my ears!';
else
{
echo 'You are so polite, so let\'s proceed with the rest of the code!';
(...)
}
Does anyone know how to write regex pattern, that does this:
let's say I have letters in array like
$letters = array('a','b','a');
and also we have a word Alabama and I want preg_match to return true, since it contains letter A two times and B. But it should return false on word Ab, because there aren't two A in that word.
Any ideas ?
EDIT: the only pattern I tried was [a,b,a] but it returns true on every word that does contain one of these letters and also doesn't check it for multiple letter occurences
I think you don't have to overcomplicate the process. You can traverse the letters and check if the exists in the word, if all the letter are there, return true. Something like this:
$letters = array('a','b','a');
$word = "Alabama";
function inWord($l,$w){
//For each letter
foreach($l as $letter){
//check if the letter is in the word
if(($p = stripos($w,$letter)) === FALSE)
//if false, return false
return FALSE;
else
//if the letter is there, remove it and move to the next one
$w = substr_replace($w,'',$p,1);
}
//If it found all the letters, return true
return TRUE;
}
And use it like this: inWord($letters,$word);
Please note this is case insensitive, if you need it case sensitive replace stripos by strpos
Must you need to use regular expressions? Even if the problem can be solved through them, the code will be very complicated.
"Manual" solution will be clearer and takes linear time:
function stringContainsAllCharacters(string $str, array $chars): bool
{
$actualCharCounts = array_count_values(str_split($str));
$requiredCharCounts = array_count_values($chars);
foreach ($requiredCharCounts as $char => $count) {
if (!array_key_exists($char, $actualCharCounts) || $actualCharCounts[$char] < $count) {
return false;
}
}
return true;
}
I'm trying to figure out a way to see if user entered search term relates to anything in the $propertyData array.
So far I have used in_array() function, but to my understanding it will only match if user entered search term matches array field exactly e.g. User entered "This is a house" and it matches first field in an array wich is "This is a house", but if user enters "This is a" or "a house" it will not match, even though these words are present in that field.
if(in_array($getSearch, $propertyData)) {
// $getSearch is user input
// $propertyData is array containing fields
}
Is there a function / way that can be used to achieve a task?
Try preg_grep(). It searches an array by regular expression and returns an array of values that matched the expression. So if anything other than an empty array is returned it is considered true:
if(preg_grep("/$getSearch/", $propertyData)) {
For case insensitive add the i modifier:
if(preg_grep("/$getSearch/i", $propertyData)) {
If you want an array of all of the values that matched (if more than 1) also, then:
if($matches = preg_grep("/$getSearch/i", $propertyData)) {
Use array_filter() in conjunction with strpos() scan your array for partial matches of the search-string and return items where a match is found:
$result = array_filter($array,
function ($item) use ($getSearch) {
return (strpos($item, $getSearch) !== FALSE);
},
$propertyData);
Alternatively, you could use preg_grep() as suggested in AbraCadaver's answer. It returns an array consisting of the elements of the input array that match the given pattern. The regular expression needs to be enclosed in delimiters. I've used / below:
// escape search pattern to allow for special characters
$searchPattern = preg_quote($getSearch, '/');
if ($arr = preg_grep("/$searchPattern/", $propertyData)) {
print_r($arr);
// ...
}
You can use something like this:
$found = FALSE;
foreach($propertyData as $property) {
if(strpos($userQuery, $property)) {
$found = TRUE;
break;
}
}
However, if $propertyData grows, this solution will get slow. Then you could use a database for this.
Use:
foreach($propertyData as $data )
{
if( strpos($data, $getSearch) )
{
//match found
}
}
I have a query string, like:
n1=v1&n2=v2&n3=v3
etc
I just want a php function that will accept the query string and the name (key), and remove the name value pair from the querystring.
Every example I have found uses regexes and assumes that the value will exist and that it will not be empty, but in my case (and possibly in general, I would like to know) this would also be a valid query:
n1=v1&n2=&n3
I don’t know in advance how many keys there will be.
I am convinced that regexes are monsters that eat time. Eventually all matter in the universe will end up in a regex.
parse_str('n1=v1&n2=&n3', $gets);
unset($gets['n3']);
echo http_build_query($gets);
NOTE: unset($gets['n3']); is just a show-case example
function stripkey($input, $key) {
$parts= explode("&", $input);
foreach($parts as $k=>$part) {
if(strpos($part, "=") !== false) {
$parts2= explode("=", $part);
if($key == $parts2[0]){
unset($parts[$k]);
}
}
}
return join("&", $parts);
}
Please excuse my noob-iness!
I have a $string, and would like to see if it contains any one or more of a group of words, words link ct, fu, sl** ETC. So I was thinking I could do:
if(stristr("$input", "dirtyword1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
elseif(stristr("$input", "dirtyWord1"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord2");
}
...ETC. BUT, I don't want to have to keep doing if/elseif/elseif/elseif/elseif...
Can't I just do a switch statement OR have an array, and then simply say something like?:
$dirtywords = { "f***", "c***", w****", "bit**" };
if(stristr("$input", "$dirtywords"))
{
$input = str_ireplace("$input", "thisWillReplaceDirtyWord");
}
I'd appreciate any help at all
Thank you
$dirty = array("fuc...", "pis..", "suc..");
$censored = array("f***", "p***", "s***");
$input= str_ireplace($dirty, $censored , $input);
Note, that you don't have to check stristr() to do a str_ireplace()
http://php.net/manual/en/function.str-ireplace.php
If search and replace are arrays, then str_ireplace() takes a value from each array and uses them to do search and replace on subject. If replace has fewer values than search, then an empty string is used for the rest of replacement values. If search is an array and replace is a string, then this replacement string is used for every value of search.
Surely not the best solution since I don't know too much PHP, but what about a loop ?
foreach (array("word1", "word2") as $word)
{
if(stristr("$input", $word))
{
$input = str_ireplace("$input", $word" "thisWillReplaceDirtyWord");
}
}
When you have several objects to test, think "loop" ;-)