Preg_Match_All: two values in a pattern
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 = appleedit: what if I had multiple items inside the开发者_高级运维 tag
ex:[tag val=100 id=3]
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];
}
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.
精彩评论