Home » Php » regex – Php get string between tags

regex – Php get string between tags

Posted by: admin July 12, 2020 Leave a comment

Questions:

I got a string like this which is (Joomla all video plugin)

{Vimeo}123456789{/Vimeo} 

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

How to&Answers:

If you must use a regular expression, 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"

This may be more than what you want to go through, 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"

Answer:

Here’s another solution for you

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

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

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

Output

tag: Vimeo, body: 123456789

Or you could build it into a function like this

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

Output

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

Answer:

You may try like this:

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

Answer:

Yes, you could use regex.Like this:

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

Answer:

If the buildup is always like that you could also replace the tags by nothing

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