1

我正在尝试制定一个 php 函数来搜索引用页面的术语,然后根据这些术语的存在执行一个函数。

创建基本代码不是问题,但是由于有相当多的单词和可选操作,脚本会变得很长,为每组单词/功能使用单独的行。基本代码概念如下。stripos 函数的优先顺序是相反的,因此如果出现两个或多个术语,那么最重要的术语排在最后,并将覆盖前面的术语

(我想可能有一种方法可以在满足第一个条件后退出脚本,但是我的退出实验失败了,所以我只使用了反向排序)

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

有没有办法使用二维数组或两个数组,一个带有单词,一个带有动作?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; }  }

...... 更新 ......

受 Phillips 建议的启发,我们最终得到了一个多维数组,然后逐步遍历它的“行”。现在正在从 MySQL 中获取数组,而不是用代码写出来。

$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']; }  }

...... 更新 ......

它已经演变为一个简单的 MySQL 查询,后跟一个 while 语句而不是一个 foreach。多亏了 Stackoverflow 上的反馈和其他各种帖子,它的工作就像一个魅力。

谢谢大家。

这个地方非常适合学习和理解,帖子直接跳到事物的本质,而不必搜索大量相关但不适用的教程。

4

2 回答 2

0

您可以将您的文字操作存储为键值数组,格式为

$actionsForWord = array("myAction" => "myword", "myAction2" => "myword2");

然后通过这些并使用 Eval 和字符串连接来调用函数: http: //php.net/manual/en/function.eval.php

但是,如果您告诉我们更多关于您实际想要实现的目标——即您想要采取哪些行动的示例,基于哪些词语?-- 可能有更好、更简洁的方式来组织你的代码。请记住,Eval 需要通过从不传递用户内容来保护它,因此只能使用您自己的“白名单”命令。

于 2011-12-03T12:06:06.533 回答
0

尽管 Philipp Lenssen 给出的答案肯定是正确的(并且被接受)并且会起作用,但我真的不喜欢使用 eval 执行功能的想法。你可以试试这个;

<?php
function search( $content, $actions ) {
    foreach( $actions as $action => $terms ) {
        foreach( $terms as $term ) {
            if( stripos( $content, $term ) !== false ) {
                /* Match found, perform $action, and return. */
                return $action( strtolower( $term ) );
            }
        }
    }
    return false;
}

function foo( $term ) {
    return "foo(): Found the term '{$term}'.";
}

function bar( $term ) {
    return "bar(): Found the term '{$term}'.";
}


$tests = array(
    'This is text containing term 1' => "foo(): Found the term 'term 1'.",
    'term 2 is in this text' => "foo(): Found the term 'term 2'.",
    'Capitals work, TERM 3' => "bar(): Found the term 'term 3'.",
    'No correct term to be found here' => false
);

$actions = array(
    'foo' => array(
        'term 1',
        'term 2'
    ),
    'bar' => array(
        'term 3'
    )
);

foreach( $tests as $content => $expected ) {
    $result = search( $content, $actions );
    echo $result . ( $result === $expected ? ' (CORRECT)' : ' (FALSE)' ) . PHP_EOL;
}

真的没有必要使用 eval ,我强烈建议不要使用它。

于 2011-12-05T13:24:35.097 回答