簡體   English   中英

如何在PHP的字符串中找到第一個匹配項?

[英]How to find the first occurrence within a string in PHP?

因此,基本上,我只是嘗試在字符串中搜索字符串。

雖然,這還有些棘手。

我有三個小弦, onetwothree

而且我有一個大字符串,該字符串保存為變量,而且很長。實際上有幾段長。

我需要創建一個函數,使我可以看到哪個字符串首先出現。

例如,這樣的字符串:

Hello, testing testing one test some more two

將返回one因為它發生在two之前。

另一個例子:

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

因為它發生在onetwo之前,所以將返回three

是否有人對此有任何建議或示例? PHP的新手,不確定要怎么做。 謝謝!

使用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'));

參見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個變量來說工作量不大。

這應該工作:

<?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);

?>

這是一個示例算法:

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。 一旦找到一個,賓果游戲。

嘗試這樣的事情:

$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

如果想花哨的話,可以將閉包與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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM