我一直在推迟问这个问题并尽可能多地研究它,但我仍然找不到解决方案。
我有一个PHP应用程序,其中将有一些令牌可以启动其他应用程序。
例如,我将有这样的变量
%APP:name_of_the_app|ID:123123123%
我需要在字符串中搜索这种类型的标签,然后提取"APP"和"ID"的值,我还有其他预定义的令牌,它们以%开头和结尾,所以如果我必须使用不同的字符来打开和关闭令牌没关系。
APP 可以是字母数字,可以包含 - 或 _ID 仅为数字
谢谢!
带有捕获组的正则表达式应该适合您(/%APP:(.*?)'|ID:([0-9]+)%/
):
$string = "This is my string but it also has %APP:name_of_the_app|ID:123123123% a bunch of other stuff in it";
$apps = array();
if (preg_match_all("/%APP:(.*?)'|ID:([0-9]+)%/", $string, $matches)) {
for ($i = 0; $i < count($matches[0]); $i++) {
$apps[] = array(
"name" => $matches[1][$i],
"id" => $matches[2][$i]
);
}
}
print_r($apps);
这给了:
Array
(
[0] => Array
(
[name] => name_of_the_app
[id] => 123123123
)
)
或者,您可以使用 strpos
和 substr
来做同样的事情,而无需指定标记的名称(不过,如果您在字符串中间使用百分号,这将出错):
<?php
$string = "This is my string but it also has %APP:name_of_the_app|ID:123123123|whatevertoken:whatevervalue% a bunch of other stuff in it";
$inTag = false;
$lastOffset = 0;
$tags = array();
while ($position = strpos($string, "%", $offset)) {
$offset = $position + 1;
if ($inTag) {
$tag = substr($string, $lastOffset, $position - $lastOffset);
$tagsSingle = array();
$tagExplode = explode("|", $tag);
foreach ($tagExplode as $tagVariable) {
$colonPosition = strpos($tagVariable, ":");
$tagsSingle[substr($tagVariable, 0, $colonPosition)] = substr($tagVariable, $colonPosition + 1);
}
$tags[] = $tagsSingle;
}
$inTag = !$inTag;
$lastOffset = $offset;
}
print_r($tags);
?>
这给了:
Array
(
[0] => Array
(
[APP] => name_of_the_app
[ID] => 123123123
[whatevertoken] => whatevervalue
)
)
演示