1

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

我有一个字符串:

$str = "hello world, this is mars"

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

istrstr($str, 'world', 'is')

返回值将是:

"world, this"

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

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

更新:

根据我做了这个功能的答案:

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);
    }

}

现在我只需要排除版本,所以我没有费心去做包括一个......

4

2 回答 2

10
function from_to($str, $from, $to) {
    return substr(
        $str,
        strpos($str, $from),
        strpos($str, $to) - strpos($str, $from) + strlen($to)
    );
}

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


关闭所有边缘情况的更强大的解决方案(并包括文档):

<?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');
}
于 2012-08-21T08:15:05.923 回答
0
function istrstr($haystack, $needle1, $needle2) {
    $pos1=strpos($haystack,$needle1);
    $pos2=strpos($haystack,$needle2);
    return substr($haystack, $pos1, $pos2-$pos1+strlen($needle2));
}
$str = "hello world, this is mars";
echo istrstr($str, 'world', 'is');

虽然这会返回,因为上面句子中world, this的第一个实例位于单词 的第 15 位。isthis

编辑:

我会推荐正则表达式,正如上面@Nanne 评论的那样,以使你有一个$needle2不在一个词中的词,如果那是你所追求的?

于 2012-08-21T08:26:20.103 回答