0

I've been holding off from asking this and researching it as much as possible but I still can't find a solution.

I have a PHP application where there will be certain tokens that will initiate other apps.

for example i will have variables like this

%APP:name_of_the_app|ID:123123123%

I need to search a string for this type of tag then extract the value of "APP" and "ID", I also have other tokens that are predefined and they start and end with % so if i have to use different characters to open and close the token that's ok.

APP can be alphanumeric and may contain - or _ ID is numeric only

Thanks!

1 Answer 1

3

A regex with capture groups should work for you (/%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);

Which gives:

Array
(
    [0] => Array
        (
            [name] => name_of_the_app
            [id] => 123123123
        )

)

Alternately, you can use strpos and substr to do the same thing without specifying what the tokens are called (this would bug up if you used a percentage sign in the middle of the string, though):

<?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);
?>

Which gives:

Array
(
    [0] => Array
        (
            [APP] => name_of_the_app
            [ID] => 123123123
            [whatevertoken] => whatevervalue
        )

)

DEMO

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.