duangutian1426 2013-09-11 02:48
浏览 195
已采纳

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

So basically, I am simply trying to search for a string within a string.

Although, it is a little trickier than that.

I have three small strings, one, two, three

And I have one large string, which is saved as a variable and is quite long.. A few paragraphs long actually.

I need to create a function that allows me to see which string occurs first.

For example, a string like this:

Hello, testing testing one test some more two

Will return one since it occurred before two.

Another example:

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

Will return three since it occurred before both one and two.

Does anyone have any suggestions or examples on how to do this? Very new to PHP and not to sure how to go about doing this. Thanks!

  • 写回答

6条回答 默认 最新

  • dongxu198714 2013-09-11 03:03
    关注

    Try something like this:

    $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;
    

    Output:

    Found one at 23
    Found two at 42
    Found three at 
    Hello, testing testing one test some more two
    FIRST: one
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(5条)

报告相同问题?

悬赏问题

  • ¥15 无线电能传输系统MATLAB仿真问题
  • ¥50 如何用脚本实现输入法的热键设置
  • ¥20 我想使用一些网络协议或者部分协议也行,主要想实现类似于traceroute的一定步长内的路由拓扑功能
  • ¥30 深度学习,前后端连接
  • ¥15 孟德尔随机化结果不一致
  • ¥15 apm2.8飞控罗盘bad health,加速度计校准失败
  • ¥15 求解O-S方程的特征值问题给出边界层布拉休斯平行流的中性曲线
  • ¥15 谁有desed数据集呀
  • ¥20 手写数字识别运行c仿真时,程序报错错误代码sim211-100
  • ¥15 关于#hadoop#的问题