php使用offset获取两个字符串之间的字符串

时间:2016-03-06 23:34:12

标签: php

function getdatabetween($string, $start, $end){
    $sp = strpos($string, $start)+strlen($start);
    $ep = strpos($string, $end)-strlen($start);
    $data = trim(substr($string, $sp, $ep));
    return trim($data);
}
$dt = "Hello cat bye Hello dog bye";
echo getdatabetween($dt, 'Hello', 'bye');

如何为此功能添加偏移?

示例:

$dt = "Hello cat bye Hello dog bye";
echo getdatabetween($dt, 'Hello', 'bye', 0); //result = cat
echo getdatabetween($dt, 'Hello', 'bye', 1); //result = dog

1 个答案:

答案 0 :(得分:0)

函数strpos实现了一个偏移参数。

试试这个

function getdatabetween($string, $start, $end, $offset){
        $sp = strpos($string, $start, $offset)+strlen($start);
        $ep = strpos($string, $end, $offset)-strlen($start);
        $data = trim(substr($string, $sp, $ep));
        return trim($data);
}