我一直没有问过这个并尽可能地研究它,但我仍然无法找到解决方案。
我有一个PHP应用程序,其中会有某些令牌会启动其他应用程序。
例如,我将有像这样的变量%APP:name_of_the_app|ID:123123123%
我需要在字符串中搜索此类型的标记,然后提取“APP”和“ID”的值,我还有其他预定义的标记,它们以%开头和结尾,所以如果我必须使用不同的字符打开和关闭正常的令牌。
APP可以是字母数字,可能包含 - 或_ ID仅为数字
谢谢!
答案 0 :(得分:3)
具有捕获组的正则表达式应该适合您(/%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
)
)