Get content between two strings PHP

Jaki jest najlepszy sposób na uzyskanie zawartości między dwoma łańcuchami np.

ob_start();
include('externalfile.html'); ## see below
$out = ob_get_contents();
ob_end_clean();

preg_match('/{FINDME}(.|\n*)+{\/FINDME}/',$out,$matches);
$match = $matches[0];

echo $match;

## I have used .|\n* as it needs to check for new lines. Is this correct?

## externalfile.html

{FINDME}
Text Here
{/FINDME}

Z jakiegoś powodu wydaje się to działać w jednym miejscu w moim kodzie, a nie w innym. Czy dobrze to robię? A może jest lepszy sposób?

Czy bufor wyjściowy jest również sposobem na to, czy file_get_contents?

Z góry dzięki!
Author: Lizard, 2009-09-18

8 answers

  • Użyj # zamiast /, więc nie musisz od nich uciekać.
  • modyfikator s sprawia, że . i \s zawierają również nowe linie.
  • { i } ma różne funkcje, takie jak od N do M razy w {n,m}.
  • Podstawowe

    preg_match('#\\{FINDME\\}(.+)\\{/FINDME\\}#s',$out,$matches);
    
  • Zaawansowane dla różnych tagów itp (stylizacja nie jest tak miła dla javascript).

    $delimiter = '#';
    $startTag = '{FINDME}';
    $endTag = '{/FINDME}';
    $regex = $delimiter . preg_quote($startTag, $delimiter) 
                        . '(.*?)' 
                        . preg_quote($endTag, $delimiter) 
                        . $delimiter 
                        . 's';
    preg_match($regex,$out,$matches);
    

Umieść ten kod w funkcji

  • dla każdego pliku, który robisz nie chcesz wykonywać żadnego kodu php, powinieneś użyć file_get_contents. include / require nie powinno być tam nawet opcji.
 39
Author: OIS,
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-09-23 16:53:57

Równie dobrze możesz użyć do tego podstr i strpos.

$startsAt = strpos($out, "{FINDME}") + strlen("{FINDME}");
$endsAt = strpos($out, "{/FINDME}", $startsAt);
$result = substr($out, $startsAt, $endsAt - $startsAt);

Musisz dodać sprawdzanie błędów, aby obsłużyć sprawę, w której nie znajdzie mnie.

 40
Author: Adam Wright,
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
2009-09-18 16:10:15

Kocham te dwa rozwiązania]}

function GetBetween($content,$start,$end)
{
    $r = explode($start, $content);
    if (isset($r[1])){
        $r = explode($end, $r[1]);
        return $r[0];
    }
    return '';
}


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

Zrobiłem również kilka benchmarków z obu powyższych rozwiązań i oba dają prawie ten sam czas. Możesz go również przetestować. Dałem obu funkcjom plik do przeczytania, który miał około 60000 znaków (sprawdzony z liczbą słów MS. Word) i obie funkcje spowodowały około 0.000999 sekund, aby znaleźć.

$startTime = microtime(true);
GetBetween($str, '<start>', '<end>');
echo "Explodin Function took: ".(microtime(true) - $startTime) . " to finish<br />";

$startTime = microtime(true);
get_string_between($str, '<start>', '<end>');
echo "Subsring Function took: ".(microtime(true) - $startTime) . " to finish<br />";
 4
Author: Abdul Jabbar Dumrai,
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-02-15 22:30:22

Podziały wierszy mogą powodować problemy w wyrażeniach regularnych, spróbuj usunąć lub zastąpić je \n przed przetworzeniem.

 1
Author: Cem Kalyoncu,
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
2009-09-18 16:12:01

Lubię unikać używania regex, jeśli to możliwe, oto alternatywne rozwiązanie do pobierania wszystkich łańcuchów między dwoma łańcuchami i zwracania tablicy.

function getBetween($content, $start, $end) {
    $n = explode($start, $content);
    $result = Array();
    foreach ($n as $val) {
        $pos = strpos($val, $end);
        if ($pos !== false) {
            $result[] = substr($val, 0, $pos);
        }
    }
    return $result;
}
print_r(getBetween("The quick brown {{fox}} jumps over the lazy {{dog}}", "{{", "}}"));

Wyniki:

Array
(
    [0] => fox
    [1] => dog
)
 1
Author: Donovan P,
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-11 03:33:45
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);
 0
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:48:15

Jest to rozwiązanie PHP, które zwraca łańcuchy znalezione pomiędzy znacznikami w stogu siana. To działa, ale nie testowałem wydajności. Potrzebowałem tego i zainspirowała mnie odpowiedź Adama Wrighta na tej stronie.

Zwraca tablicę zawierającą wszystkie łańcuchy występujące pomiędzy $tag i $end_symbold.$tag in $haystack, OR FALSE if no $end_symbol.$tag został znaleziony w związku z tym w $haystack nie istnieje żadna para tagów.

function str_between_tags($haystack, $tag, $end_symbol){
    $c_end_tags = substr_count($haystack, $end_symbol.$tag);
    if(!$c_end_tags) return FALSE;

    for($i=0; $i<$c_end_tags; $i++){
        $p_s = strpos($haystack, $tag, (($p_e)?$p_e+strlen($end_symbol.$tag):NULL) ) + strlen($tag );
        $p_e = strpos($haystack, $end_symbol.$tag, $p_s);
        $result[] = substr($haystack, $p_s, $p_e - $p_s);
    }
    return $result;
}
 0
Author: dalv lexa,
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-18 16:00:32

Szybki sposób, aby umieścić wszystko w jednym sznurku.

$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$one_string = str_replace($newlines, "", html_entity_decode($content));
 -1
Author: Bob,
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
2012-12-17 23:42:55