How to write a bann function in php? - php

I have an array of many banned string and i have a small string contains one keywords, too and i want to write a function in php like this:
function is_ban($keyword,$bannedList) {
}
where $keyword is small string and $bannedList is an array like
Array
(
[0] => php
[1] => html
[2] => java
[3] => css
[....]
)
The function check keyword in banned list and return true or false.

function is_ban($keyword,$bannedList) {
return in_array($keyword, $bannedList);
}

This is my first reply on a php related question. As others have said, if you have a precisely defined array of banned words, and you have already taken the time to get the word $keyword from the user, then by all means just use PHP's native function in_array(). You may however need to do the following:
if(in_array(strtolower($keyword), $bannedList)){ //return true }
Just make sure of course that your $bannedList array is all lowercase as well. If however you need to do pattern matches inside longer strings, then you'll need to resort to regular expressions.

This is a simple way to define your function
function is_ban($keyword,$bannedList)
{
return in_array($keyword, $bannedList);
}

Related

PHP doesn't find array elements

A library I use uses an array. Applying print_r to that array prints this:
Array
(
[*queueId] => 1
[*handle] => 9b875867b36d568483fb35fdb8b0bbf6
[*body] => First string in the TestQueue
[*md5] => c23ba714199666efbc1dcd5659bb0a0a
[*timeout] => 1408003330.6534
[*id] => 2
[*creationdate] => 2014-08-13 16:03:37
)
The library uses a magic getter on that array
public function __get($key)
{
if (!array_key_exists($key, $this->_data)) {
throw new Exception\InvalidArgumentException("Specified field \"$key\" is not in the message");
}
return $this->_data[$key];
}
When I try to access
$myObject->body
I run into the exception. In fact, the debugger shows that array_key_exists will return false while the _data array is available as printed above
The asterisk indicates that this array is a representation of an object, probably the original object property is protected.
http://php.net/manual/en/language.types.array.php#language.types.array.casting
As I explained in the comments, the array keys actually start with an asterisk. Since you can't call them using the regular syntax of $obj->*body (it'll cause a syntax error), you can use the following:
$myObject->{'*body'}
This should solve your problem.
Assuming that $myObject is the array you are talking from:
You can't access arrays with ->, use $myObject['*body'] instead. (And you should as well change the name to $myArray, for example)
As #MarkBaker stated in the comment of my question, the problem was that I was serializing an object with private properties to the array. The asterisk were marks that these properties were private.

How would I build a simple php hook system that works like this?

I am trying to figure out a way to build a hook system very similar to the one that Drupal uses. With Drupal you can simply name a function a certain way and it will automatically be invoked as a hook if the module is enabled.
I have looked at the other answers here on Stackoverflow, but none of them really give an answer of how to build this type of feature into a PHP application.
This is how drupal does it, and how you can do it.
Using string concatenation with name convention.
With function_exists() and call_user_func_array() you should be all set.
Here are the two internal drupal functions that make the trick (module.inc)
function module_invoke() {
$args = func_get_args();
$module = $args[0];
$hook = $args[1];
unset($args[0], $args[1]);
$function = $module .'_'. $hook;
if (module_hook($module, $hook)) {
return call_user_func_array($function, $args);
}
}
function module_hook($module, $hook) {
return function_exists($module .'_'. $hook);
}
Therefore, you only need to invoke
module_invoke('ModuleName','HookName', $arg1, $arg2, $arg3);
which will finally call
ModuleName_HookName($arg1,$arg2,$arg3);
You could use PHP's get_defined_functions to get an array of strings of function names, then filter those names by some predefined format.
This sample from the PHP docs:
<?php
function myrow($id, $data)
{
return "<tr><th>$id</th><td>$data</td></tr>\n";
}
$arr = get_defined_functions();
print_r($arr);
?>
Outputs something like this:
Array
(
[internal] => Array
(
[0] => zend_version
[1] => func_num_args
[2] => func_get_arg
[3] => func_get_args
[4] => strlen
[5] => strcmp
[6] => strncmp
...
[750] => bcscale
[751] => bccomp
)
[user] => Array
(
[0] => myrow
)
)
It's kinda a sketchy technique when compared to a more explicit hook system, but it works.
I'm not familiar with Drupal internals, but it probably does it using Reflection:
http://php.net/manual/en/book.reflection.php
You would include the PHP page that contains the hook functions, then use reflection to find functions or class methods that match a certain naming convention, then save function-pointers to call those functions when appropriate (such as events in a module's lifecycle).
Why not just use function exist? The developer could name the function in a certain way, and the hook codes just check that it exist then call them

Search in array with relevance

I am doing a very small online store application in PHP. So I have an array of maps in PHP. I want to search for a string (a product) in the array. I looked at array_search in PHP and it seems that it only looks for exact match. Do you guys know a better way to do this functionality? Since this is a very small part of what I am actually doing, I was hoping that there was something built in. Any ideas?
Thanks!
EDIT: The array contains "products" in this format:
[6] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 2000-YM
)
[Name] => Team Swim School T-Shirt
[size] => YM
[price] => 15
[group] => Team Clothing
[id] => 2000-YM
)
[7] => SimpleXMLElement Object
(
[#attributes] => Array
(
[id] => 3000-YS
)
[Name] => Youth Track Jacket
[size] => YS
[price] => 55
[group] => Team Clothing
[id] => 3000-YS
)
So I was wondering I can do a search such as "Team" and it would return me first item seen here. I am basing the search on the Name (again this is just something small). I understand that I can find the exact string, I am just stuck on the "best results" if it cannot find the exact item. Efficiency is nice but not required since I only have about 50 items so even if I use a "slow" algorithm it won't take much time.
array_filter lets you specify a custom function to do the searching. In your case, a simple function that uses strpos() to check if your search string is present:
function my_search($haystack) {
$needle = 'value to search for';
return(strpos($haystack, $needle)); // or stripos() if you want case-insensitive searching.
}
$matches = array_filter($your_array, 'my_search');
Alternatively, you could use an anonymous function to help prevent namespace contamination:
$matches = array_filter($your_array, function ($haystack) use ($needle) {
return(strpos($haystack, $needle));
});
foreach($array as $item){
if(strpos($item,"mysearchword")!== false){
echo 'found';
}
}
or you can use preg_match for more flexible search instead of strpos.
I think Marc B's answer was a good starting point but for me it had some problems. Such as you have to know what the Needle is at "compile time" because you can't dynamically change that value. also if the needle appeared at the start of the string element it would act like it's not there at all. so after a little experimenting I manged to come up with a way around both problems. so you don't have to create a new function for every different needle your going to want to use anymore.
function my_search($haystack)
{
global $needle;
if( strpos($haystack, $needle) === false) {return false;} else {return true;}
}
and it would be called like this:
$needle="item to search for";
$matches = array_filter($my_array, 'my_search');
and being as needle is now accessible in the same scope that the rest of the code is you can set needle to any other string variable you wanted, including user input.
Unfortunately, search is one of the more difficult things to do in computer science. If you build for search based on literal string matches or regular expressions (regex), you may find that you'll be unhappy with the relevance of the results that are returned.
If you're interested in rolling up your sleeves and getting a little dirty with a more sophisticated solution, I'd try Zend's Lucene implementation ( http://framework.zend.com/manual/en/zend.search.lucene.html ). I've implemented a search on a site with it. It took a few days, but the results were MUCH better than the 15 minute solution of literal string matching.
PS. Here's an example: http://devzone.zend.com/article/91
I have same Issue but i have created i function to search in array by passing the array, key and value.
public function searchinarr($array, $key, $value)
{
$results = array();
for($i=0;$i<count($array);$i++)
{
foreach($array[$i] as $k=>$val)
{
if($k==$key)
{
if(strpos($val,$value)!== false)
{
$results[] = $array[$i];
}
}
}
}
return $results;
}

How to create wordpress like functions in PHP?

To pass variables into functions, I do the following (as other people I'm sure):
function addNums($num1, $num2)
{
$num1 + $num2;
}
addNums(2, 2);
My question is how would I structure a function to act like Wordpress:
wp_list_categories('title_li=');
Essentially I am looking for a way to create a key/value pair in my functions.
Any advice is appreciated.
parse_str() should do what you want: http://www.php.net/parse_str
You can use parse_str to parse the string for arguments. The tricky thing is that you may not want to just allow any and all parameters to get passed in. So here's an example of only allowing certain parameters to be used when they're passed in.
In the following example, only foo, bar and valid would be allowed.
function exampleParseArgs($arg_string) {
// for every valid argument, include in
// this array with "true" as a value
$valid_arguments = array(
'foo' => true,
'bar' => true,
'valid' = true,
);
// parse the string
parse_str($arg_string, $parse_into);
// return only the valid arguments
return array_intersect_key($parse_into,$valid_arguments);
}
baz will be dropped because it is not listed in $valid_arguments. So for this call:
print_r(exampleParseArgs('foo=20&bar=strike&baz=50'));
Results:
Array
(
[foo] => 20
[bar] => strike
)
Additionally, you can browse the Wordpress Source code here, and of course by downloading it from wordpress.org. Looks like they do something very similar.

PHP architecture, and pass-by-reference vs pass-by-value

Seeking suggestions from PHP architects!
I'm not terribly familiar with PHP but have taken over maintenance of a large analytics package written in the language. The architecture is designed to read reported data into large key/value arrays, which are passed through various parsing modules to extract those report parameters known to each of those modules. Known parameters are removed from the master array, and any leftovers which were not recognized by any of the modules, are dumped into a kind of catch-all report showing the "unknown" data points.
There are a few different methods being used to call these parser modules, and I would like to know which if any are considered to be "proper" PHP structure. Some are using pass-by-reference, others pass-by-value, some are functions, some are objects. All of them modify the input parameter in some way.
A super-simplified example follows:
#!/usr/bin/php
<?php
$values = Array("a"=>1, "b"=>2, "c"=>3, "d"=>4 );
class ParserA {
private $a = null;
public function __construct(&$myvalues) {
$this->a = $myvalues["a"];
unset($myvalues["a"]);
}
public function toString() { return $this->a; }
}
// pass-by-value
function parse_b($myvalues) {
$b = $myvalues["b"];
unset($myvalues["b"]);
return Array($b, $myvalues);
}
// pass-by-reference
function parse_c(&$myvalues) {
echo "c=".$myvalues["c"]."\n";
unset($myvalues["c"]);
}
// Show beginning state
print_r($values);
// will echo "1" and remove "a" from $values
$a = new ParserA($values);
echo "a=".$a->toString()."\n";
print_r($values);
// w ill echo "2" and remove "b" from $values
list($b, $values) = parse_b($values);
echo "b=".$b."\n";
print_r($values);
// will echo "3" and remove "c" from $values
parse_c($values);
print_r($values);
?>
The output will be:
Array
(
[a] => 1
[b] => 2
[c] => 3
[d] => 4
)
a=1
Array
(
[b] => 2
[c] => 3
[d] => 4
)
b=2
Array
(
[c] => 3
[d] => 4
)
c=3
Array
(
[d] => 4
)
I'm really uncomfortable having so many different call methods in use, some of which have hidden effects on the call function parameters using "&pointer"-style functions, some requiring the main body to write their output, and some writing their output independently.
I would prefer to choose a single methodology and stick with it. In order to do so, I would also like to know which is most efficient; my reading of the PHP documentation indicates that since it uses copy-on-write, there shouldn't be much performance difference between using pointers to vs passing the object directly and re-reading a return value. I would also prefer to use the object-oriented structure, but am uncomfortable with the hidden changes being made to the input parameter on the constructor.
Of the three calling methods, ParserA(), parse_b(), and parse_c(), which if any is the most appropriate style?
I'm not really an expert in PHP but from my experience passing by value is better. This way code won't have side effects and that mean it will be easier to understand and maintain and do all sorts of crazy things on it, like using it as callback for map function. So I'm all for parse_b way of doing things.
FYI: In PHP, objects are always passed by reference, no matter what. Also if you have an array with objects and scalar values in it, the scalar values are passed by value, but the objects by reference.
As a general rule in PHP, do not use references unless you really have to.
references in PHP are also not what most people expect them to be:
"References in PHP are a means to access the same variable content by different names. They are not like C pointers; instead, they are symbol table aliases.""
see also: php.net: What References Are
So in short:
The proper way of handling this PHP is using creating an object that passes the variables around by value or manipulating the array with array_map (array_map allows you to apply a callback function to the elements an array.)
I would vote against the methods proposed in general, but of them, I think parse_b has the best idea.
I think it would be better design to wrap the "data" array in a class that could let you "pop" a key out of it easily. So the parser ends up looking like:
class ParserA {
private $a = null;
public function __construct(My_Data_Class $data) {
$this->a = $data->popValue("a");
}
public function toString() { return $this->a; }
}
And a sample implementation
class My_Data_Class {
protected $_data;
public function __construct(array $data) {
$this->_data = $data;
}
public function popValue($key) {
if (isset($this->_data[$key])) {
$value = $this->_data[$key];
unset($this->_data[$key]);
return $value;
}
}
}

Categories