开发者

Preg_Match_All: two values in a pattern

开发者 https://www.devze.com 2023-01-18 13:30 出处:网络
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]

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]


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.

0

精彩评论

暂无评论...
验证码 换一张
取 消