I have custom tags [tag val=100][/tag]
. How do I get val
and whatever goes between the tags?
ex:
[tag val=100]apple[/tag]
value1 = 100
value2 = apple
edit: what if I had multiple items inside the tag
ex:
[tag val=100 id=3]
I have custom tags [tag val=100][/tag]
. How do I get val
and whatever goes between the tags?
ex:
[tag val=100]apple[/tag]
value1 = 100
value2 = apple
edit: what if I had multiple items inside the tag
ex:
[tag val=100 id=3]
This would be a regular expression for it:
'#\[tag val=([0-9]+)\]([a-zA-Z]+)\[\/tag])#'
Val would be a number and your 'apple' can be one or more occurences of alphabetic characters. Replace [a-zA-Z]+
by .+?
if you want to match more characters.
If you have a string like that in your question, you can use preg_match
instead of preg_match_all
:
$str = "[tag val=100]apple[/tag]";
preg_match("/\[.+? val=(.+?)\](.+?)\[\/.+?\]/", $str, $matches);
$value = $matches[1]; // "100"
$content = $matches[2]; // "apple"
Update: I see you might have multiple attributes in each element. In that case, this should work:
// captures all attributes in one group, and the value in another group
preg_match("/\[.+?((?:\s+.+?=.+?)+)\](.+?)\[\/.+?\]/", $str, $matches);
$attributes = $matches[1];
$content = $matches[2];
// split attributes into multiple "key=value" pairs
$param_pairs = preg_split("/\s+/", $attributes, -1, PREG_SPLIT_NO_EMPTY);
// create dictionary of attributes
$params = array();
foreach ($param_pairs as $pair) {
$key_value = explode("=", $pair);
$params[$key_value[0]] = $key_value[1];
}