php - 带有结束针的strstr

Mos*_*ham 1 php

可能重复:
如何使用PHP解析和处理HTML?
PHP - 通过搜索字符获取字符串的一部分,而不是计算它们?

我有一个字符串:

$str = "hello world, this is mars"
Run Code Online (Sandbox Code Playgroud)

我想要一个改进的strstr,看起来像这样:

istrstr($str, 'world', 'is')
Run Code Online (Sandbox Code Playgroud)

并且返回值将是:

"world, this"
Run Code Online (Sandbox Code Playgroud)

换句话说,有一根针开始,一根针结束.

我只是想知道是否已经有解决方案,或者我应该自己写一个...

更新:

基于答案,我做了这个功能:

function istrstr($haystack, $needle_start, $needle_end, $include = false) {

    if (!$include) {
        $pos_start = strpos($haystack, $needle_start) + strlen($needle_start);
        $pos_end = strpos($haystack, $needle_end, $pos_start);
        return substr($haystack, $pos_start, $pos_end - $pos_start);
    }

}
Run Code Online (Sandbox Code Playgroud)

现在我只需要排除版本,所以我没有打扰包括一个......

Mad*_*iha 10

function from_to($str, $from, $to) {
    return substr(
        $str,
        strpos($str, $from),
        strpos($str, $to) - strpos($str, $from) + strlen($to)
    );
}
Run Code Online (Sandbox Code Playgroud)

这是基本的字符串操作.请多阅读本手册.


一个更强大的解决方案来关闭所有边缘案例(包括文档):

<?php

/**
 * @param string $string  The string to match against
 * @param string $from    Starting substring, from here
 * @param string $to      Ending substring, to here
 *
 * @return string         Substring containing all the letters from $from to $to inclusive.
 * @throws Exception      In case of $to being found before $from
 */
function from_to($string, $from, $to) {
    //Calculate where each substring is found inside of $string
    $pos_from = strpos($string, $from);
    $pos_to   = strpos($string, $to);

    //The function will break if $to appears before $from, throw an exception.
    if ($pos_from > $pos_to) {
        throw new Exception("'$from' ($pos_from) appears before '$to' ($pos_to)");
    }

    return substr(
        $string,
        $pos_from, //From where the $from starts (first character of $from)
        $pos_to - $pos_from + strlen($to) //To where the $to ends. (last character of $to)
    );
}

$str = "hello world, and this not foo is mars";
try {
    echo from_to($str, 'world', 'hell');
}
catch (Exception $e) {
    //In case 'hell' appeared before 'world'
    echo from_to($str, 'hell', 'world');
}
Run Code Online (Sandbox Code Playgroud)