在php中的字符串中查找子字符串的最佳方法


Best way to find a sub string in a string in php

我有一个字符串,比如$str="欢迎来到我家";

从上面的字符串中如何找到$substr='tomy';

我可以使用作为子字符串的子字符串函数

substr($str,startposition , length);

我不知道我的子字符串的确切位置,上面我举了一个例子。我的子字符串可能在第一个位置,可能在中间位置,也可能在最后一个位置。

可以通过3步实现

$position = strpos( 'welcome to my home' , 'to my');
$length = strlen('to my');
$mysubstr = substr($str,$position,$length);

但有没有优化的解决方案?

$position = strpos( 'welcome to my home' , 'to my');

计数从0开始,因此在上面的示例中,$position将等于8。