Php gets a line between tags

I have a line like this (Joomla all video plugin)

{Vimeo}123456789{/Vimeo} 

where 123456789 is a variable, how can I extract this? Should I use regex?

+5
source share
5 answers

If you must use a regex, the following will do the trick.

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

It may be more than you want, but here is a way to avoid 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" 
+8
source

Here is another solution for you

 $str = "{Vimeo}123456789{/Vimeo}"; preg_match("/\{(\w+)\}(.+?)\{\/\\1\}/", $str, $matches); printf("tag: %s, body: %s", $matches[1], $matches[2]); 

Exit

 tag: Vimeo, body: 123456789 

Or you could build it as a function

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

Exit

 array(2) { [0]=> string(9) "123456789" [1]=> string(3) "123" } 
+4
source

You can try the following:

 $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); } 
+2
source

Yes, you can use regex.Like:

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

If the extension always seems like you can also replace the tags with nothing.

 $string = '{Vimeo}123456789{/Vimeo}'; str_replace(array('{Vimeo}', '{/Vimeo}'), '', $string); 
+1
source

Source: https://habr.com/ru/post/1202450/


All Articles