如何在PHP中查找字符串中的第一个匹配项?

时间:2013-09-11 02:48:56

标签: php string

所以基本上,我只是想在字符串中搜索一个字符串。

尽管如此,它有点棘手。

我有三个小字符串,onetwothree

我有一个大字符串,它被保存为变量并且很长。实际上有几段长。

我需要创建一个允许我查看首先出现哪个字符串的函数。

例如,像这样的字符串:

Hello, testing testing one test some more two

因为它发生在one之前将返回two

另一个例子:

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

three onetwo之前发生后,将返回{{1}}。

有没有人有关于如何做到这一点的任何建议或例子?非常新的PHP,不知道如何去做这件事。谢谢!

6 个答案:

答案 0 :(得分:3)

使用preg_match()进行简单的替换:

if (preg_match('/one|two|three/', $string, $matches)) {
    echo $matches[0];
}

结果:

Hello, testing testing one test some more two
-> one

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

如果你也需要这个职位,你可以添加一个标志:

if (preg_match('/one|two|three/', $string, $matches, PREG_OFFSET_CAPTURE)) {
    echo 'Found ' . $matches[0][0] . ' @ ' . $matches[0][1];
}

作为一项功能:

function findFirst($string, array $needles)
{
    $pattern = '/' . join('|', array_map(function($str) {
        return preg_quote($str, '/');
    }, $needles)) . '/';

    if (preg_match($pattern, $string, $matches)) {
        return $matches[0];
    } else {
        return false;
    }
}

使用:

echo findFirst($string, array('one', 'two', 'three'));

答案 1 :(得分:1)

请参阅http://www.php.net/manual/en/function.strpos.php

简单地说就像

$longString = "Hello, testing testing one test some more two";
$onePosition = strpos($longString, "one");
$twoPosition = strpos($longString, "two");
$threePosition = strpos($longString, "three");

$onePosition; // 23
$twoPosition; // 42
$threePosition; // -1

然后你只需要比较每个变量以找到最低的变量。笨重,但3个变量没什么用。

答案 2 :(得分:1)

这应该有效:

<?php

    $arrWords = array("one", "two", "three");
    $strInput = "Test a paragraph three and testing some more one test test two";

    function getFirstOccurrence($strInput, $arrWords) {
        $arrInput = explode(" ", $strInput);
        foreach($arrInput as $strInput) {
            if(in_array($strInput, $arrWords)) {
                return $strInput;
            }
        }
        return null;
    }

    print "First word is: " . getFirstOccurrence($strInput, $arrWords);

?>

答案 3 :(得分:1)

以下是一个示例算法:

function getFirstWord(array $needles, $haystack) {
    $best = null; //the best position
    $first = null; //the first word

    foreach($needles as $needle) {
        $pos = strpos($haystack, $needle);
        if($pos !== false) {
            if($best === null || $pos < $best) {
                $best = $pos;
                $first = $needle;
            }
        }
    }

    //returns the first word, or null if none of $needles found
    return $first;
}

$needles = array('one', 'two', 'three');
echo getFirstWord($needles, 'Hello, testing testing one test some more two'); // one
echo getFirstWord($needles, 'Test a paragraph three and testing some more one test test two'); // three

最佳解决方案可以最大限度地减少超过$ haystack的迭代次数。您可以从字符串的开头开始,每次前进一个字符时,查找从当前位置开始的任何$ needle。只要你找到一个宾果游戏。

答案 4 :(得分:1)

尝试这样的事情:

$string = 'Hello, testing testing one test some more two';
$words = Array("one", "two", "three");
$low_pos = strlen($string);
$first = '';
foreach($words as $word)
{
    $pos = strpos($string, $word);
    echo "Found ".$word." at ".$pos."<br />";
    if($pos !== false && $pos < $low_pos)
    {
        $low_pos = $pos;
        $first = $word;
    }
}

echo $string."<br />";
echo "FIRST: ".$first;

输出:

Found one at 23
Found two at 42
Found three at 
Hello, testing testing one test some more two
FIRST: one

答案 5 :(得分: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