0

我有自定义标签[tag val=100][/tag]。我如何获得val标签之间的内容?

前任:

[tag val=100]apple[/tag]  

值 1 = 100
值 2 = 苹果

编辑:如果我在标签内有多个项目怎么办

[tag val=100 id=3]
4

2 回答 2

2

如果您的问题中有这样的字符串,则可以使用preg_match代替preg_match_all

$str = "[tag val=100]apple[/tag]";

preg_match("/\[.+? val=(.+?)\](.+?)\[\/.+?\]/", $str, $matches);

$value = $matches[1];    // "100"
$content = $matches[2];  // "apple"

更新:我看到每个元素中可能有多个属性。在这种情况下,这应该有效:

// 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];
}
于 2010-10-04T20:28:54.313 回答
1

这将是它的正则表达式:

'#\[tag val=([0-9]+)\]([a-zA-Z]+)\[\/tag])#'

Val 将是一个数字,您的“苹果”可以是一个或多个字母字符的出现。如果要匹配更多字符,请替换[a-zA-Z]+为。.+?

于 2010-10-04T20:21:23.780 回答