與捕獲組A的正則表達式應該爲你工作(/%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
)
)
DEMO
這是完美的!非常感謝!!! –