I am trying to work out a php function to search the referring page for terms and then perform a function based on the existence of those terms.
Creating the basic code wasn’t an issue, but with a fairly large number of words and optional actions, the script is getting quite long using individual lines for each group of words/function. The basic code concept is below. The stripos functions are in reverse order of preference, so that if two or more terms appear, then the most important ones are last and will over ride the previous ones
(I imagine there maybe a way to exit the script after the first condition is met, but my experiments with exit failed, so I just used reverse sequencing).
group1 = array("word1","word2","word3","word4","word5");
group2 = array("word6","word7","word8");
group3 ... etc
foreach($group1 as $groupa) { if(stripos($string, $groupa) !== false) { do something A; } }
foreach($group2 as $groupb) { if(stripos($string, $groupb) !== false) { do something B; } }
foreach ... etc
Is there a way to use a two dimensional array or two arrays, one with words and one with action ? ie:
words = array("word1","word2","word3","word4","word5","word6","word7","word8")
actions = array("something A","something A","something A","something A","something A","something B","something B","something B")
foreach($words as $word) { if(stripos($string, $word) !== false) { do actions; } }
…… UPDATED ……
Inspired by Phillips suggestion, we ended up with a multidimensional array and then stepped through its “rows”. Now working on fetching the array from MySQL rather than writing it out in code.
$terms = array(
array( "word" => "word1",
"cat" => "dstn",
"value" => "XXXX"
),
..etc
..etc
);
foreach ($terms as $i => $row)
{ if(stripos($refstring3, $row['word']) !== false) { $$row['cat'] = $row['value']; } }
…… UPDATED ……
It has evolved to a simple MySQL query, followed by a while statement rather than a foreach. Works like a charm, thanks to feedback and various other posts on Stackoverflow.
Thanks to all.
This place is great for learning and understanding, posts jump straight to the meat of things and skip having to search through numerous related but inapplicable tutorials.
You could store your word-actions as a key-value array in the form of
then go through these and use Eval and string concatenation to call the function: http://php.net/manual/en/function.eval.php
However, if you tell us more about what you actually want to achieve — i.e. what are some examples of actions you want to take, based on what words? — there may be much better and cleaner ways to organize your code. And keep in mind that Eval needs to be secured by never passing it user content, so only work with your own “whitelisted” commands.