Question

I have this URL: ../foo::bar{2}233{13}171{1}1{20}0.html

Parameters are in {}, values behind.

With this I'm able to get one parameter - despite the curly braces:

if (false !== strpos($url,'{2}')) {
        echo 'success';
    } else {
        echo 'error';
}

I want to get each value behind the {} .

Was it helpful?

Solution

Try using preg_match_all()

$str = '../foo::bar{2}233{13}171{1}1{20}0.html';

$pattern = "/\{\d+\}/";

preg_match_all($pattern, $str, $matches);

$prevStart = 0;
foreach($matches[0] as $match)
{
    $matchLen = strlen($match);
    $matchPos = strpos($str, $match, $prevStart);

    // Try to find the position of the next open curly brace
    $openCurlyPos = strpos($str, '{', $matchPos + $matchLen);

    // In case there is none found (.html comes up next), search for the . instead
    if($openCurlyPos === false)
        $openCurlyPos = strpos($str, '.', $matchPos + $matchLen);

    $length = $openCurlyPos - ($matchPos + $matchLen);

    $prevStart = $openCurlyPos;
    echo $match.': '.substr($str, $matchPos + $matchLen, $length).'<br />';
}

/*
Result:

{2}: 233
{13}: 171
{1}: 1
{20}: 0
*/

I know this way might be pretty redundant, but I have no idea how to do this using regex. This also seems simpler to figure out for people.

OTHER TIPS

Using preg_match_all you can extract the keys and values, here's a sample pattern to do so;

$matches = null;
$returnValue = preg_match_all('/\\{(\\d+)\\}(\\d+)\\b/', '../foo::bar{2}233{13}171{1}1{20}0.html', $matches, PREG_SET_ORDER);

If we ignore the double escaping, it does as follows;

  • Find a {
  • 1 or more digits, until a }
  • 1 or more digits, until a word boundary appears

try this.

$pieces = explode("}", $str);

get all odd index elements.

$pieces[1],$pieces[3],$pieces[5]

etc...

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top