2014-09-12 20 views
5

ho ottenuto una stringa come questa che è (Joomla tutti i video plug-in)Php stringa di ottenere tra i tag

{Vimeo}123456789{/Vimeo} 

dove 123456789 è variabile, come posso estrarre questo? Devo usare regex?

+0

Yep, regex farà questo. Prova qui: http://regex101.com. – halfer

+0

Duplicato di http://stackoverflow.com/questions/5696412/get-substring-between-two-strings-php – skrilled

+1

Righto, tre persone hanno messo in svantaggio questo? Con il quale affermano che: "Questa domanda mostra uno sforzo di ricerca, è utile e chiaro"? (vedi il testo al passaggio del mouse). – halfer

risposta

8

Se si deve usare un'espressione regolare, il seguente farà il trucco.

$str = 'foo {Vimeo}123456789{/Vimeo} bar'; 
preg_match('~{Vimeo}([^{]*){/Vimeo}~i', $str, $match); 
var_dump($match[1]); // string(9) "123456789" 

Questo può essere più di ciò che si vuole passare, ma qui è un modo per evitare regex.

$str = 'foo {Vimeo}123456789{/Vimeo} bar'; 
$m = substr($str, strpos($str, '{Vimeo}')+7); 
$m = substr($m, 0, strpos($m, '{/Vimeo}')); 
var_dump($m); // string(9) "123456789" 
+0

fantastico, grazie. Non sono abbastanza bravo con regex – asdf23e32

1

Sì, è possibile utilizzare questo regex.Like:

preg_match_all('/{Vimeo}(.*?){\/Vimeo}/s', $yourstring, $matches); 
+1

La barra del middle forward richiederà la ricerca di escape. Su una nota più ampia, nessun impegno è stato speso dal PO, e potrebbe non essere un favore per la comunità rispondendo a questo tipo di domande. – halfer

+0

@derdida Grazie mille! Nessuno degli esempi sopra ha funzionato per il mio scenario, ma il tuo lo ha fatto. Non ascoltare l'halfer, continua a postare le domande se hai altri modi per risolvere un problema. – adamj

2

Si può provare in questo modo:

$string = '{Vimeo}123456789{/Vimeo} '; 

echo extractString($string, '{Vimeo}', '{/Vimeo}'); 

function extractString($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); 
} 
1

Se l'accumulo è sempre così si potrebbe anche sostituire i tag dal nulla

$string = '{Vimeo}123456789{/Vimeo}'; 
str_replace(array('{Vimeo}', '{/Vimeo}'), '', $string); 
4

Ecco un'altra soluzione per voi

$str = "{Vimeo}123456789{/Vimeo}"; 

preg_match("/\{(\w+)\}(.+?)\{\/\\1\}/", $str, $matches); 

printf("tag: %s, body: %s", $matches[1], $matches[2]); 

uscita

tag: Vimeo, body: 123456789 

Oppure si potrebbe costruire in una funzione come questa

function getTagValues($tag, $str) { 
    $re = sprintf("/\{(%s)\}(.+?)\{\/\\1\}/", preg_quote($tag)); 
    preg_match_all($re, $str, $matches); 
    return $matches[2]; 
} 

$str = "{Vimeo}123456789{/Vimeo} and {Vimeo}123{/Vimeo}"; 

var_dump(getTagValues("Vimeo", $str)); 

uscita

array(2) { 
    [0]=> 
    string(9) "123456789" 
    [1]=> 
    string(3) "123" 
} 
Problemi correlati