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

时间:2015-02-11 09:23:55

标签: php

我有一个字符串可以说$ str ='welcome to my home';

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

我可以使用substr

的子串函数
substr($str,startposition , length);

我不知道我的子串的确切位置,上面我提到的一个例子。我的子串可能处于第一位置,可能处于中间位置,可能处于最后位置。

可以通过3个步骤实现

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

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

1 个答案:

答案 0 :(得分:0)

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

计数从0开始,所以在上面的例子中,$ position将等于8。