Domanda

Qual è il modo migliore per ottenere il contenuto tra due stringhe, ad esempio

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}

Per qualche motivo questo sembra funzionare in un punto del mio codice e non in un altro. Sto andando nel modo giusto? O c'è un modo migliore?

Anche il buffer di output è il modo per fare questo o file_get_contents?

Grazie in anticipo!

È stato utile?

Soluzione

  • Usa # invece di / in modo da non doverli sfuggire.
  • Il modificatore s rende . e \ s includono anche le nuove righe.
  • { e } ha varie funzionalità come da n a m volte in {n, m} .
  • La base

    preg_match('#\\{FINDME\\}(.+)\\{/FINDME\\}#s',$out,$matches);
    
  • L'avanzato per vari tag ecc. (lo stile non è così carino con il javascript).

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

Metti questo codice in una funzione

  • Per qualsiasi file che non si desidera eseguire alcun codice php randagio , è necessario utilizzare file_get_contents. include / request non dovrebbe nemmeno essere un'opzione lì.

Altri suggerimenti

Puoi anche usare substr e strpos per questo.

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

Dovrai aggiungere il controllo degli errori per gestire il caso in cui non FINDME.

Adoro queste due soluzioni

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

Ho anche fatto pochi benchmark con entrambe le soluzioni sopra ed entrambe stanno dando quasi lo stesso tempo. Puoi anche provarlo. Ho dato a entrambe le funzioni un file da leggere che conteneva circa 60000 caratteri (rivisto con il conteggio delle parole della signora Word) ed entrambe le funzioni hanno prodotto circa 0.000999 secondi da trovare.

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

Le interruzioni di riga possono causare problemi in RegEx, provare a rimuoverle o sostituirle con \ n prima dell'elaborazione.

Mi piace evitare di usare regex se possibile, ecco una soluzione alternativa per recuperare tutte le stringhe tra due stringhe e restituire un array.

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}}", "{{", "}}"));

Risultati:

Array
(
    [0] => fox
    [1] => dog
)
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);

Questa è una soluzione PHP che restituisce le stringhe trovate tra i tag in un pagliaio. Funziona, ma non ho testato l'efficienza. Ne avevo bisogno e mi sono ispirato alla risposta di Adam Wright in questa pagina.

Restituisce un array () contenente tutte le stringhe trovate tra $ tag e $ end_symbold. $ tag nel pagliaio $, o FALSE se non è stato trovato alcun $ end_symbol. $ tag quindi nessuna coppia di tag esiste nel $ pagliaio.

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

Modo rapido per mettere tutto in una stringa.

$newlines = array("\t","\n","\r","\x20\x20","\0","\x0B");
$one_string = str_replace($newlines, "", html_entity_decode($content));
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top