Jak uzyskać podłańcuch między dwoma łańcuchami w PHP?

Potrzebuję funkcji, która zwraca podłańcuch pomiędzy dwoma słowami (lub dwoma znakami). Zastanawiam się, czy istnieje funkcja php, która to osiąga. Nie chcę myśleć o regex (cóż, mógłbym zrobić jeden, ale naprawdę nie sądzę, że to najlepszy sposób, aby przejść). Myślenie o funkcjach strpos i substr. Oto przykład:

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

Wywołujemy funkcję: $substring = getInnerSubstring($string,"foo");
Powraca: "i wanna a cake".

Z góry dzięki.

Aktualizacja: Cóż, aż teraz mogę po prostu dostać substring beteen dwa słowa w jednym łańcuchu, czy pozwolisz mi pójść trochę dalej i zapytać, Czy Mogę rozszerzyć użycie getInnerSubstring($str,$delim), aby uzyskać dowolne łańcuchy, które są między wartością delim, przykład:

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

Otrzymuję tablicę jak {"I like php", "I also like asp", "I feel hero"}.

Author: slick, 2011-04-18

30 answers

[Foo] & [/foo]), spójrz na ten post od Justina Cooka. Kopiuję jego kod poniżej:

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)
 234
Author: Alejandro García Iglesias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-29 06:33:30

Wyrażenia regularne to droga:

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

OnlinePhp

 39
Author: nbrogi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-23 15:49:25
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 '';
    }
}

Użycie próbki:

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

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

echo getBetween("a","r","World"); // returns: ''
 22
Author: daniel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-08 11:50:07
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] : '';
}

Przykład użycia:

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

Jeśli chcesz usunąć otaczające białe znaki, użyj trim. Przykład:

var_dump(trim(getInnerSubstring('foo Hello world foo','foo')));
// prints: string(11) "Hello world"
 12
Author: Christian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-17 21:11:49
function getInbetweenStrings($start, $end, $str){
    $matches = array();
    $regex = "/$start([a-zA-Z0-9_]*)$end/";
    preg_match_all($regex, $str, $matches);
    return $matches[1];
}

Dla examle chcesz tablicę łańcuchów (kluczy) pomiędzy @@ w następujący sposób przykład, gdzie ' / ' nie mieści się pomiędzy

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

print_r($str_arr);
 11
Author: Ravi Verma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-02-26 15:46:58

Jeśli używasz foo jako ogranicznika, spójrz na explode()

 6
Author: oblig,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2011-04-17 21:08:08

Lubię rozwiązania wyrażeń regularnych, ale żadne z pozostałych mi nie odpowiada.

Jeśli wiesz, że będzie tylko 1 wynik możesz użyć następującego:

$between = preg_replace('/(.*)BEFORE(.*)AFTER(.*)/sm', '\2', $string);

Zmień przed i PO na żądane ograniczniki.

Należy również pamiętać, że funkcja zwróci cały łańcuch w przypadku, gdy nic nie pasuje.

To rozwiązanie jest Wielowierszowe, ale możesz grać modyfikatorami w zależności od potrzeb.

 5
Author: ragnar,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-09-03 12:36:00
<?php
  function getBetween($content,$start,$end){
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
  }
?>

Przykład:

<?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;
?>

To zwróci "facet w środku".

 4
Author: user1366605,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-10 06:10:36

Użyj funkcji strstr php dwa razy.

$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;

Wyjścia: "is a great day to"

 4
Author: Bryce,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-06-13 21:29:16

Jeśli masz wiele powtórzeń z jednego łańcucha i masz inny wzór [start] i [\end]. Oto funkcja, która wyświetla tablicę.

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;
}
 3
Author: noelthegreat,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-10-27 08:48:45

Oto funkcja

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

Użyj go jak

$string = "foo I wanna a cake foo";
$substring = getInnerSubstring($string, "foo");

echo $substring;

Output (zwróć uwagę, że zwraca spacje z przodu i Na oraz Twojego ciągu znaków, jeśli istnieją)

I wanna a cake

Jeśli chcesz przyciąć wynik użyj funkcji

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

Result : funkcja zwróci false Jeśli $boundstring nie został znaleziony w $string lub jeśli $boundstring istnieje tylko raz w $string, w przeciwnym razie zwraca podłańcuch pomiędzy pierwszym i ostatnim wystąpieniem $boundstring w $string.


Referencje
 2
Author: Wh1T3h4Ck5,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-17 10:28:59

Użycie:

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

?>
 1
Author: Salim,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-08 05:49:33

Trochę ulepszony kod od GarciaWebDev i Henry Wang. Jeśli podano pusty $start lub $ end, funkcja zwraca wartości od początku lub do końca łańcucha$. Dostępna jest również opcja Inclusive, niezależnie od tego, czy chcemy dołączyć wynik wyszukiwania, czy nie:

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);
}
 1
Author: Julius Tilvikas,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-11-05 13:18:38

Muszę coś dodać do postu Juliusa Tilvikasa. Szukałem takiego rozwiązania jak to, które opisał w swoim poście. Ale myślę, że to pomyłka. Nie dostaję naprawdę struny między dwoma strunami, dostaję też Więcej z tym rozwiązaniem, ponieważ muszę odjąć długość struny startowej. Kiedy to zrobię, naprawdę dostanę strunę między dwoma strunami.

Oto moje zmiany jego rozwiązania:

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

Greetz

V

 1
Author: Der_V,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-12-04 07:17:43

Spróbuj tego, jego praca dla mnie, Pobierz dane pomiędzy test word.

$str = "Xdata test HD01 test 1data";  
$result = explode('test',$str);   
print_r($result);
echo $result[1];
 1
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-11-10 06:09:28

W Stylu PHP strpos zwróci to false, jeśli znacznik początkowy sm lub końcowy em nie zostaną znalezione.

Ten wynik (false) jest inny od pustego ciągu, który otrzymujesz, jeśli nie ma nic między znacznikami początku i końca.

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

Funkcja zwróci tylko pierwsze dopasowanie.

To oczywiste, ale warto wspomnieć, że funkcja najpierw będzie szukać sm, a następnie dla em.

Oznacza to, że możesz nie otrzymać pożądanego wynik / zachowanie, jeśli em ma być najpierw przeszukiwane, a następnie łańcuch musi być przetransferowany wstecz w poszukiwaniu sm.

 1
Author: Paolo,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-01-27 12:23:18

Nie jest php pro. ale ostatnio też wpadłem na tę ścianę i właśnie to wymyśliłem.

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
)
 1
Author: Light93,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-05-08 18:16:39

Używam

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

Napis dla dowolnego ogranicznika, który chcesz.

 1
Author: Ángel R.G.,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-04-25 08:18:00

Użycie:

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');
 0
Author: Pankaj Raturi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-10-03 12:38:34

Miałem pewne problemy z funkcją get_string_between (), używaną tutaj. Więc przyszedłem z własną wersją. Może to pomoże ludziom w tej samej sprawie co moja.

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;
}
 0
Author: KmeCnin,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-15 22:23:22

Napisał je jakiś czas temu, uznał, że są bardzo przydatne w szerokim zakresie zastosowań.

<?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);
}
?>
 0
Author: Dave,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-12-22 23:14:52

Z pewnym błędem. W szczególności, większość prezentowanych funkcji wymaga istnienia $end, podczas gdy w rzeczywistości w moim przypadku potrzebowałem, aby była opcjonalna. Użyj tego, że $end jest opcjonalne i oceń jako FALSE, jeśli $start w ogóle nie istnieje:

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

}
 0
Author: NotaGuruAtAll,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-12-01 18:53:42

Wersja UTF-8 odpowiedzi @ Alejandro Iglesias, będzie działać dla znaków innych niż łacińskie:

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)
 0
Author: NXT,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-06 12:13:51

To jest funkcja, której do tego używam. Połączyłem dwie odpowiedzi w jedną funkcję dla jednego lub wielu ograniczników.

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

Do prostego użycia (zwraca dwa):

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

Dla uzyskania każdego wiersza w tabeli do tablicy wyników:

$result = getStringBetweenDelimiters($table, '<tr>', '</tr>', true);
 0
Author: Szekelygobe,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-06 20:12:50

Najlepsze rozwiązanie dla tego od tonyspiro

function getBetween($content,$start,$end){
   $r = explode($start, $content);
   if (isset($r[1])){
       $r = explode($end, $r[1]);
       return $r[0];
   }
   return '';
}
 0
Author: Som,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-03-22 07:25:57

Poprawa odpowiedź Alejandro . Możesz pozostawić argumenty $start lub $end puste i użyje początku lub końca łańcucha.

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);
    }
}
 0
Author: Rikki Masters,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-07-25 09:36:20

Używam tego od lat i działa dobrze. Prawdopodobnie może być bardziej wydajny, ale

Grabstring ("test string","","",0) Zwraca Test string
grabstring ("test string", "Test","", 0) zwraca string
grabstring ("test string","s","", 5) zwraca string

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

}

 -1
Author: carbroker,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-27 01:49:03
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));
}

Użycie:

echo strbtwn($s,"<h2>","</h2>");//<h2>:)</h2> --> :)
 -1
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-09-23 15:37:41

"/s "

function getStrBetween($left, $right, $in)
{
    preg_match('/'.$left.'(.*?)'.$right.'/s', $in, $match);
    return empty($match[1]) ? NULL : $match[1];
}

Spróbuj tego;)

 -1
Author: GigolNet Guigolachvili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-02-26 21:11:29
echo explode('/', explode(')', $string)[0])[1];

Zastąp ' / ' pierwszym znakiem/ciągiem znaków i ')' końcowym znakiem / ciągiem znaków. :)

 -1
Author: OMi Shah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-03-07 08:30:09