1

つまり、基本的に、文字列内の文字列を検索しようとしているだけです。

ただし、それよりも少しトリッキーです。

私は 3 つの小さな文字列を持っています, one, two,three

そして、変数として保存され、非常に長い 1 つの大きな文字列があります。実際には数段落の長さです。

最初に出現する文字列を確認できる関数を作成する必要があります。

たとえば、次のような文字列です。

Hello, testing testing one test some more two

one以前に発生したため、戻りtwoます。

もう一つの例:

Test a paragraph three and testing some more one test test two

threeの両方の前に発生したため、戻ります。onetwo

これを行う方法についての提案や例はありますか? PHP は初めてで、これを行う方法がわかりません。ありがとう!

4

6 に答える 6

0

凝りたい場合は、array_map、array_filter、array_search、および min でクロージャを使用できます。

function whichFirst(array $list, $string){
    // get a list of the positions of each word
    $positions = array_map(function($val) use ($string){
                                return strpos($string, $val);
                            }, $list);
    // remove all of the unfound words (where strpos returns false)
    $positions = array_filter($positions, function ($x){ return $x !== false; });

    // get the value with the key matching the lowest position.
    $key = array_search(min($positions), $positions);

    return $list[$key];
}

例:

$str = "Hello, testing testing one test some more two";
$list = ["one","two","three"];

echo whichFirst($list, $str);
// outputs one
于 2013-09-11T03:16:16.490 に答える