如何在PHP中获取两个字符串之间的子字符串?

时间:2011-04-17 21:01:17

标签: php substring

我需要一个函数来返回两个单词(或两个字符)之间的子串。 我想知道是否有一个PHP功能实现了这一点。我不想考虑正则表达式(好吧,我可以做一个,但真的不认为这是最好的方式)。考虑strpossubstr函数。 这是一个例子:

$string = "foo I wanna a cake foo";

我们称之为功能:$substring = getInnerSubstring($string,"foo");
它回归:“我想要一块蛋糕。”

提前致谢。

更新 好吧,到现在为止,我只能在一个字符串中得到一个字符串只有两个字,你是否允许让我走得更远,并问我是否可以扩展使用getInnerSubstring($str,$delim)以获得介于两者之间的任何字符串delim value,例如:

$string =" foo I like php foo, but foo I also like asp foo, foo I feel hero  foo";

我得到一个像{"I like php", "I also like asp", "I feel hero"}这样的数组。

36 个答案:

答案 0 :(得分:265)

如果字符串不同(即:[foo]& [/ foo]),请查看Justin Cook的this post。 我复制下面的代码:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}

$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');

echo $parsed; // (result = dog)

答案 1 :(得分:53)

正则表达式是要走的路:

$str = 'before-str-after';
if (preg_match('/before-(.*?)-after/', $str, $match) == 1) {
    echo $match[1];
}

onlinePhp

答案 2 :(得分:22)

function getBetween($string, $start = "", $end = ""){
    if (strpos($string, $start)) { // required if $start not exist in $string
        $startCharCount = strpos($string, $start) + strlen($start);
        $firstSubStr = substr($string, $startCharCount, strlen($string));
        $endCharCount = strpos($firstSubStr, $end);
        if ($endCharCount == 0) {
            $endCharCount = strlen($firstSubStr);
        }
        return substr($firstSubStr, 0, $endCharCount);
    } else {
        return '';
    }
}

样品使用:

echo getBetween("a","c","abc"); // returns: 'b'

echo getBetween("h","o","hello"); // returns: 'ell'

echo getBetween("a","r","World"); // returns: ''

答案 3 :(得分:13)

function getInnerSubstring($string,$delim){
    // "foo a foo" becomes: array(""," a ","")
    $string = explode($delim, $string, 3); // also, we only need 2 items at most
    // we check whether the 2nd is set and return it, otherwise we return an empty string
    return isset($string[1]) ? $string[1] : '';
}

使用示例:

var_dump(getInnerSubstring('foo Hello world foo','foo'));
// prints: string(13) " Hello world "

如果要删除周围的空格,请使用trim。例如:

var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"

答案 4 :(得分:12)

function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

例如,您希望在以下示例中@@之间的字符串(键)数组,其中'/'不介于

之间
$str = "C://@@ad_custom_attr1@@/@@upn@@/@@samaccountname@@";
$str_arr = getInbetweenStrings('@@', '@@', $str);

print_r($str_arr);

答案 5 :(得分:8)

我喜欢正则表达式解决方案,但其他人都不适合我。

如果您知道只有1个结果,您可以使用以下内容:

m3.xlarge | CORES : 4(1) | RAM : 15 (3.5) | HDD : 80 GB | Nodes : 3 Nodes

spark-submit --class <YourClassFollowedByPackage> --master yarn-cluster --num-executors 2 --driver-memory 8g --executor-memory 8g --executor-cores 1 <Your Jar with Full Path> <Jar Args>

将BEFORE和AFTER更改为所需的分隔符。

另请注意,如果没有匹配,此函数将返回整个字符串。

此解决方案是多线的,但您可以根据需要使用修改器。

答案 6 :(得分:6)

如果您使用foo作为分隔符,请查看explode()

答案 7 :(得分:5)

<?php
  function getBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
  }
?>

示例:

<?php 
  $content = "Try to find the guy in the middle with this function!";
  $start = "Try to find ";
  $end = " with this function!";
  $output = getBetween($content,$start,$end);
  echo $output;
?>

这将返回“中间人”。

答案 8 :(得分:4)

两次使用strstr php函数。

$value = "This is a great day to be alive";
$value = strstr($value, "is"); //gets all text from needle on
$value = strstr($value, "be", true); //gets all text before needle
echo $value;

输出: "is a great day to"

答案 9 :(得分:3)

如果您有一个字符串的多次重复,并且您有不同的[start]和[\ end]模式。 这是一个输出数组的函数。

function get_string_between($string, $start, $end){
    $split_string       = explode($end,$string);
    foreach($split_string as $data) {
         $str_pos       = strpos($data,$start);
         $last_pos      = strlen($data);
         $capture_len   = $last_pos - $str_pos;
         $return[]      = substr($data,$str_pos+1,$capture_len);
    }
    return $return;
}

答案 10 :(得分:3)

这是一个功能

function getInnerSubstring($string, $boundstring, $trimit=false) {
    $res = false;
    $bstart = strpos($string, $boundstring);
    if ($bstart >= 0) {
        $bend = strrpos($string, $boundstring);
        if ($bend >= 0 && $bend > $bstart)
            $res = substr($string, $bstart+strlen($boundstring), $bend-$bstart-strlen($boundstring));
    }
    return $trimit ? trim($res) : $res;
}

一样使用它
$string = "foo I wanna a cake foo";
$substring = getInnerSubstring($string, "foo");

echo $substring;

输出(请注意,如果存在,则返回前面和字符串处的空格)

  

我想要一块蛋糕

如果你想修剪结果使用功能,如

$substring = getInnerSubstring($string, "foo", true);

结果:如果在$boundstring中找不到$string$boundstring只存在一次,则此函数将返回 false $string,否则它会在$boundstring$string的第一次和最后一次出现之间返回子字符串。

<小时/> <强>参考

答案 11 :(得分:2)

不是php专业版。但我最近也碰到了这堵墙,这就是我想出来的。

function tag_contents($string, $tag_open, $tag_close){
   foreach (explode($tag_open, $string) as $key => $value) {
       if(strpos($value, $tag_close) !== FALSE){
            $result[] = substr($value, 0, strpos($value, $tag_close));;
       }
   }
   return $result;
}

$string = "i love cute animals, like [animal]cat[/animal],
           [animal]dog[/animal] and [animal]panda[/animal]!!!";

echo "<pre>";
print_r(tag_contents($string , "[animal]" , "[/animal]"));
echo "</pre>";

//result
Array
(
    [0] => cat
    [1] => dog
    [2] => panda
)

答案 12 :(得分:1)

我用

if (count(explode("<TAG>", $input))>1){
      $content = explode("</TAG>",explode("<TAG>", $input)[1])[0];
}else{
      $content = "";
}

Subtitue&lt; TAG&gt;无论你想要什么分隔符。

答案 13 :(得分:1)

来自GarciaWebDev和Henry Wang的一些改进代码。如果给出空$ start或$ end,则函数返回$ string的开头或结尾的值。如果我们想要包含搜索结果,还可以使用包含选项:

function get_string_between ($string, $start, $end, $inclusive = false){
    $string = " ".$string;

    if ($start == "") { $ini = 0; }
    else { $ini = strpos($string, $start); }

    if ($end == "") { $len = strlen($string); }
    else { $len = strpos($string, $end, $ini) - $ini;}

    if (!$inclusive) { $ini += strlen($start); }
    else { $len += strlen($end); }

    return substr($string, $ini, $len);
}

答案 14 :(得分:1)

这是我正在使用的功能。我将一个函数中的两个答案合并为单个或多个分隔符。

function getStringBetweenDelimiters($p_string, $p_from, $p_to, $p_multiple=false){
    //checking for valid main string  
    if (strlen($p_string) > 0) {
        //checking for multiple strings 
        if ($p_multiple) {
            // getting list of results by end delimiter
            $result_list = explode($p_to, $p_string);
            //looping through result list array 
            foreach ( $result_list AS $rlkey => $rlrow) {
                // getting result start position
                $result_start_pos   = strpos($rlrow, $p_from);
                // calculating result length
                $result_len         =  strlen($rlrow) - $result_start_pos;

                // return only valid rows
                if ($result_start_pos > 0) {
                    // cleanying result string + removing $p_from text from result
                    $result[] =   substr($rlrow, $result_start_pos + strlen($p_from), $result_len);                 
                }// end if 
            } // end foreach 

        // if single string
        } else {
            // result start point + removing $p_from text from result
            $result_start_pos   = strpos($p_string, $p_from) + strlen($p_from);
            // lenght of result string
            $result_length      = strpos($p_string, $p_to, $result_start_pos);
            // cleaning result string
            $result             = substr($p_string, $result_start_pos+1, $result_length );
        } // end if else 
    // if empty main string
    } else {
        $result = false;
    } // end if else 

    return $result;


} // end func. get string between

简单使用(返回两个):

$result = getStringBetweenDelimiters(" one two three ", 'one', 'three');

将表中的每一行都放到结果数组中:

$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);

答案 15 :(得分:1)

Alejandro's answer的改进。您可以将$start$end参数保留为空,它将使用字符串的开头或结尾。

echo get_string_between("Hello my name is bob", "my", ""); //output: " name is bob"

private function get_string_between($string, $start, $end){ // Get
    if($start != ''){ //If $start is empty, use start of the string
        $string = ' ' . $string;
        $ini = strpos($string, $start);
        if ($ini == 0) return '';
        $ini += strlen($start);
    }
    else{
        $ini = 0;
    }

    if ($end == '') { //If $end is blank, use end of string
        return substr($string, $ini);
    }
    else{
        $len = strpos($string, $end, $ini) - $ini; //Work out length of string
        return substr($string, $ini, $len);
    }
}

答案 16 :(得分:1)

使用:

<?php

$str = "...server daemon started with pid=6849 (parent=6848).";
$from = "pid=";
$to = "(";

echo getStringBetween($str,$from,$to);

function getStringBetween($str,$from,$to)
{
    $sub = substr($str, strpos($str,$from)+strlen($from),strlen($str));
    return substr($sub,0,strpos($sub,$to));
}

?>

答案 17 :(得分:1)

我必须在Julius Tilvikas的帖子中添加一些东西。我寻找他在帖子中描述的解决方案。但我认为有一个错误。我没有得到两个字符串之间的字符串,我也得到更多的解决方案,因为我必须减去start-string的长度。当这样做时,我真的得到两个字符串之间的字符串。

以下是我对其解决方案的更改:

function get_string_between ($string, $start, $end, $inclusive = false){
    $string = " ".$string;

    if ($start == "") { $ini = 0; }
    else { $ini = strpos($string, $start); }

    if ($end == "") { $len = strlen($string); }
    else { $len = strpos($string, $end, $ini) - $ini - strlen($start);}

    if (!$inclusive) { $ini += strlen($start); }
    else { $len += strlen($end); }

    return substr($string, $ini, $len);
}

格尔茨

V

答案 18 :(得分:1)

试试这个,它为我工作,在测试字之间获取数据。

$str = "Xdata test HD01 test 1data";  
$result = explode('test',$str);   
print_r($result);
echo $result[1];

答案 19 :(得分:1)

在PHP的strpos样式中,如果找不到开始标记false或结束标记sm,则会返回em

此结果(false)与空字符串的不同,如果开始和结束标记之间没有任何内容,则会获得该字符串。

function between( $str, $sm, $em )
{
    $s = strpos( $str, $sm );
    if( $s === false ) return false;
    $s += strlen( $sm );
    $e = strpos( $str, $em, $s );
    if( $e === false ) return false;
    return substr( $str, $s, $e - $s );
}

该功能仅返回第一场比赛。

很明显但值得一提的是,该功能首先会查找sm,然后查找em

这意味着如果必须首先搜索em,然后必须向后解析字符串以搜索sm,则可能无法获得所需的结果/行为。

答案 20 :(得分:0)

这里的绝大多数答案都无法回答编辑过的部分,我想它们是以前添加的。正如一个答案所提到的,可以使用正则表达式来完成。我有不同的方法。


此函数搜索$ string并找到$ strong和$ start字符串之间的第一个字符串,从$ offset位置开始。然后,它更新$ offset位置以指向结果的开始。如果$ includeDelimiters为true,则在结果中包括定界符。

如果未找到$ start或$ end字符串,则返回null。如果$ string,$ start或$ end为空字符串,则它还会返回null。

function str_between(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?string
{
    if ($string === '' || $start === '' || $end === '') return null;

    $startLength = strlen($start);
    $endLength = strlen($end);

    $startPos = strpos($string, $start, $offset);
    if ($startPos === false) return null;

    $endPos = strpos($string, $end, $startPos + $startLength);
    if ($endPos === false) return null;

    $length = $endPos - $startPos + ($includeDelimiters ? $endLength : -$startLength);
    if (!$length) return '';

    $offset = $startPos + ($includeDelimiters ? 0 : $startLength);

    $result = substr($string, $offset, $length);

    return ($result !== false ? $result : null);
}

以下函数查找两个字符串之间的所有字符串(无重叠)。它需要上一个函数,并且参数相同。执行后,$ offset指向最后找到的结果字符串的开头。

function str_between_all(string $string, string $start, string $end, bool $includeDelimiters = false, int &$offset = 0): ?array
{
    $strings = [];
    $length = strlen($string);

    while ($offset < $length)
    {
        $found = str_between($string, $start, $end, $includeDelimiters, $offset);
        if ($found === null) break;

        $strings[] = $found;
        $offset += strlen($includeDelimiters ? $found : $start . $found . $end); // move offset to the end of the newfound string
    }

    return $strings;
}

示例:

str_between_all('foo 1 bar 2 foo 3 bar', 'foo', 'bar')给出[' 1 ', ' 3 ']

str_between_all('foo 1 bar 2', 'foo', 'bar')给出[' 1 ']

str_between_all('foo 1 foo 2 foo 3 foo', 'foo', 'foo')给出[' 1 ', ' 3 ']

str_between_all('foo 1 bar', 'foo', 'foo')给出[]

答案 21 :(得分:0)

亚历杭德罗·加西亚·伊格莱西亚斯写的经编辑的版本。

这使您可以根据发现结果的次数来选择要获取的字符串的特定位置。

function get_string_between_pos($string, $start, $end, $pos){
    $cPos = 0;
    $ini = 0;
    $result = '';
    for($i = 0; $i < $pos; $i++){
      $ini = strpos($string, $start, $cPos);
      if ($ini == 0) return '';
      $ini += strlen($start);
      $len = strpos($string, $end, $ini) - $ini;
      $result = substr($string, $ini, $len);
      $cPos = $ini + $len;
    }
    return $result;
  }

用法:

$text = 'string has start test 1 end and start test 2 end and start test 3 end to print';

//get $result = "test 1"
$result = $this->get_string_between_pos($text, 'start', 'end', 1);

//get $result = "test 2"
$result = $this->get_string_between_pos($text, 'start', 'end', 2);

//get $result = "test 3"
$result = $this->get_string_between_pos($text, 'start', 'end', 3);

strpos还有一个附加的可选输入,可以从特定点开始搜索。因此我将先前的位置存储在$ cPos中,以便再次进行for循环检查时,它从停止的位置开始。

答案 22 :(得分:0)

function img($n,$str){

    $first=$n."tag/";
    $n+=1;
    $last=$n."tag/";
    $frm = stripos($str,$first);
    $to = stripos($str,$last);
    echo $frm."<br>";
    echo $to."<br>";
    $to=($to=="")?(strlen($str)-$frm):($to-$frm);
    $final = substr($str,$frm,$to);
    echo $to."<br>";
    echo $final."<br>";

}


$str = "1tag/Ilove.php2tag/youlike.java3tag/youlike.php";
img(1,$str);

img(2,$str);

img(3,$str);

答案 23 :(得分:0)

使用此小功能可以轻松完成此操作:

public interface IParser
{
    List<object> Parse();
    bool SupportsParsing(string key);
}

public class EventHandler : IHandler
{
    private readonly IParser _parser;
    public EventHandler(IParser parser)
    {
        _parser = parser;
    }
    public void Handle()
    { }
}

public class EventHandlerFactory
{
    private readonly IEnumerable<IParser> _parsers;

    public EventHandlerFactory(IEnumerable<IParser> parsers)
    {
        _parsers = parsers;
    }

    public IHandler Create(string key)
    {
        foreach (var parser in _parsers)
        {
            if (parser.SupportsParsing(key))
            {
                return new EventHandler(parser);
            }
        }
        throw new NotImplementedException();
    }
}

答案 24 :(得分:0)

考虑此功能。它接受位置编号和字符串参数:

total_dummy_rec

结果:

function get_string_between($string, $start = '', $end = ''){
    if (empty($start)) {
      $start = 0;
    }elseif (!is_numeric($start)) {
      $start = strpos($string, $start) + strlen($start);
    }

    if (empty($end)) {
      $end = strlen($string);
    }elseif (!is_numeric($end)) {
      $end = strpos($string, $end);
    }

    return substr($string, $start, ($end - $start));
  }

答案 25 :(得分:0)

在 php 中获取特定文本并推送到数组中:

<!DOCTYPE html>
<html>
<body>

<?php
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}


$fullstring = '.layout { 

color: {{ base_color }} 

}

li { 

color: {{ sub_color }} 

} 

.text { 

color: {{ txt_color }}

 }

 .btn { 

color: {{ btn_color }}

 }

.more_text{

color:{{more_color}}

}';


$arr = [];

while(1){
  $parsed = get_string_between($fullstring, '{{', '}}');
  if(!$parsed)
    break;
  array_push($arr,$parsed);
  $strposition = strpos($fullstring,"}}");
  $nextString = substr($fullstring, $strposition+1, strlen($fullstring));
  $fullstring = $nextString;
  echo "<br>";
}
print_r($arr);

?>

</body>
</html>

没有数组:

<?php
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}


$fullstring = '.layout { 

color: {{ base_color }} 

}

li { 

color: {{ sub_color }} 

} 

.text { 

color: {{ txt_color }}

 }

 .btn { 

color: {{ btn_color }}

 }

.more_text{

color:{{more_color}}

}';


while(1){
  $parsed = get_string_between($fullstring, '{{', '}}');
  if(!$parsed)
    break;
  echo $parsed;
  $strposition = strpos($fullstring,"}}");
  $nextString = substr($fullstring, $strposition+1, strlen($fullstring));
  $fullstring = $nextString;
  echo "<br>";
}

?>

对于单个输出,删除数组和循环。

<?php
function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = strpos($string, $start);
    if ($ini == 0) return '';
    $ini += strlen($start);
    $len = strpos($string, $end, $ini) - $ini;
    return substr($string, $ini, $len);
}


$fullstring = '.layout { 

color: {{ base_color }} 

}

li { 

color: {{ sub_color }} 

} 

.text { 

color: {{ txt_color }}

 }

 .btn { 

color: {{ btn_color }}

 }

.more_text{

color:{{more_color}}

}';

  $parsed = get_string_between($fullstring, '{{', '}}');
  echo $parsed;

?>

答案 26 :(得分:0)

private function getStringBetween(string $from, string $to, string $haystack): string
{
    $fromPosition = strpos($haystack, $from);
    $toPosition = strpos($haystack, $to, $fromPosition);
    $betweenLength = $toPosition - $fromPosition;
    return substr($haystack, $fromPosition, $betweenLength);
}

答案 27 :(得分:0)

tonyspiro

获得最佳解决方案
function getBetween($content,$start,$end){
   $r = explode($start, $content);
   if (isset($r[1])){
       $r = explode($end, $r[1]);
       return $r[0];
   }
   return '';
}

答案 28 :(得分:0)

@Alejandro Iglesias的UTF-8版本答案,适用于非拉丁字符:

function get_string_between($string, $start, $end){
    $string = ' ' . $string;
    $ini = mb_strpos($string, $start, 0, 'UTF-8');
    if ($ini == 0) return '';
    $ini += mb_strlen($start, 'UTF-8');
    $len = mb_strpos($string, $end, $ini, 'UTF-8') - $ini;
    return mb_substr($string, $ini, $len, 'UTF-8');
}

$fullstring = 'this is my [tag]dog[/tag]';
$parsed = get_string_between($fullstring, '[tag]', '[/tag]');

echo $parsed; // (result = dog)

答案 29 :(得分:0)

有一些错误捕获。具体来说,所提出的大多数功能都需要$ end存在,而实际上在我的情况下我需要它是可选的。使用这个是$ end是可选的,如果$ start根本不存在,则评估为FALSE:

function get_string_between( $string, $start, $end ){
    $string = " " . $string;
    $start_ini = strpos( $string, $start );
    $end = strpos( $string, $end, $start+1 );
    if ($start && $end) {
        return substr( $string, $start_ini + strlen($start), strlen( $string )-( $start_ini + $end ) );
    } elseif ( $start && !$end ) {
        return substr( $string, $start_ini + strlen($start) );
    } else {
        return FALSE;
    }

}

答案 30 :(得分:0)

一段时间后写了这些,发现它对广泛的应用程序非常有用。

<?php

// substr_getbykeys() - Returns everything in a source string that exists between the first occurance of each of the two key substrings
//          - only returns first match, and can be used in loops to iterate through large datasets
//          - arg 1 is the first substring to look for
//          - arg 2 is the second substring to look for
//          - arg 3 is the source string the search is performed on.
//          - arg 4 is boolean and allows you to determine if returned result should include the search keys.
//          - arg 5 is boolean and can be used to determine whether search should be case-sensative or not.
//

function substr_getbykeys($key1, $key2, $source, $returnkeys, $casematters) {
    if ($casematters === true) {
        $start = strpos($source, $key1);
        $end = strpos($source, $key2);
    } else {
        $start = stripos($source, $key1);
        $end = stripos($source, $key2);
    }
    if ($start === false || $end === false) { return false; }
    if ($start > $end) {
        $temp = $start;
        $start = $end;
        $end = $temp;
    }
    if ( $returnkeys === true) {
        $length = ($end + strlen($key2)) - $start;
    } else {
        $start = $start + strlen($key1);
        $length = $end - $start;
    }
    return substr($source, $start, $length);
}

// substr_delbykeys() - Returns a copy of source string with everything between the first occurance of both key substrings removed
//          - only returns first match, and can be used in loops to iterate through large datasets
//          - arg 1 is the first key substring to look for
//          - arg 2 is the second key substring to look for
//          - arg 3 is the source string the search is performed on.
//          - arg 4 is boolean and allows you to determine if returned result should include the search keys.
//          - arg 5 is boolean and can be used to determine whether search should be case-sensative or not.
//

function substr_delbykeys($key1, $key2, $source, $returnkeys, $casematters) {
    if ($casematters === true) {
        $start = strpos($source, $key1);
        $end = strpos($source, $key2);
    } else {
        $start = stripos($source, $key1);
        $end = stripos($source, $key2);
    }
    if ($start === false || $end === false) { return false; }
    if ($start > $end) {
        $temp = $start; 
        $start = $end;
        $end = $temp;
    }
    if ( $returnkeys === true) {
        $start = $start + strlen($key1);
        $length = $end - $start;
    } else {
        $length = ($end + strlen($key2)) - $start;  
    }
    return substr_replace($source, '', $start, $length);
}
?>

答案 31 :(得分:0)

我在这里使用的get_string_between()函数遇到了一些问题。所以我带着我自己的版本。也许它可以帮助与我相同的人。

protected function string_between($string, $start, $end, $inclusive = false) { 
   $fragments = explode($start, $string, 2);
   if (isset($fragments[1])) {
      $fragments = explode($end, $fragments[1], 2);
      if ($inclusive) {
         return $start.$fragments[0].$end;
      } else {
         return $fragments[0];
      }
   }
   return false;
}

答案 32 :(得分:0)

使用:

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 = "Find string between two strings in PHP";
echo getdatabetween($dt, 'Find', 'in PHP');

答案 33 :(得分:-1)

echo explode('/', explode(')', $string)[0])[1];

用你的第一个字符/字符串替换'/',用你的结束字符/字符串替换')'。 :)

答案 34 :(得分:-1)

我多年来一直在使用它,效果很好。可能会提高效率,但

grabstring(&#34;测试字符串&#34;,&#34;&#34;,&#34;&#34;,0)返回测试字符串
grabstring(&#34;测试字符串&#34;,&#34;测试&#34;,&#34;&#34;,0)返回字符串
grabstring(&#34;测试字符串&#34;,&#34; s&#34;,&#34;&#34;,5)返回字符串

function grabstring($strSource,$strPre,$strPost,$StartAt) {
if(@strpos($strSource,$strPre)===FALSE && $strPre!=""){
    return("");
}
@$Startpoint=strpos($strSource,$strPre,$StartAt)+strlen($strPre);
if($strPost == "") {
    $EndPoint = strlen($strSource);
} else {
    if(strpos($strSource,$strPost,$Startpoint)===FALSE){
        $EndPoint= strlen($strSource);
    } else {
        $EndPoint = strpos($strSource,$strPost,$Startpoint);
    }
}
if($strPre == "") {
    $Startpoint = 0;
}
if($EndPoint - $Startpoint < 1) {
    return "";
} else {
        return substr($strSource, $Startpoint, $EndPoint - $Startpoint);
}

}

答案 35 :(得分:-1)

function strbtwn($s,$start,$end){
    $i = strpos($s,$start);
    $j = strpos($s,$end,$i);
    return $i===false||$j===false? false: substr(substr($s,$i,$j-$i),strlen($start));
}

用法:

echo strbtwn($s,"<h2>","</h2>");//<h2>:)</h2> --> :)