Question

I want to grab a specific string only if a certain word is followed by a = sign.

Also, I want to get all the info after that = sign until a / is reached or the string ends.

Let's take into example:

somestring.bla/test=123/ohboy/item/item=capture

I want to get item=capture but not item alone.

I was thinking about using lookaheads but I'm not sure it this is the way to go. I appreciate any help as I'm trying to grasp more and more about regular expressions.

Was it helpful?

Solution 2

If you want to capture item=capture, it is straightforward:

/item=[^\/]*/

If you want to also extract the value,

/item=([^\/]*)/

If you only want to match the value, then you need to use a look-behind.

/(?<=item=)[^\/]*/

EDIT: too many errors due to insomnia. Also, screw PHP and its failure to disregard separators in a character group as separators.

OTHER TIPS

[^/=]*=[^/]*

will give you all the pairs that match your requirements.

So from your example it should return:

test=123

item=capture

Refiddle Demo

Here is a function I wrote some time ago. I modified it a little, and added the $keys argument so that you can specify valid keys:

function getKeyValue($string, Array $keys = null) {
    $keys = (empty($keys) ? '[\w\d]+' : implode('|', $keys));
    $pattern = "/(?<=\/|$)(?P<key>{$keys})\s*=\s*(?P<value>.+?)(?=\/|$)/";
    preg_match_all($pattern, $string, $matches, PREG_SET_ORDER);
    foreach ($matches as & $match) {
        foreach ($match as $key => $value) {
            if (is_int($key)) {
                unset($match[$key]);
            }
        }
    }
    return $matches ?: FALSE;
}

Just trow in the string and valid keys:

$string = 'somestring.bla/test=123/ohboy/item/item=capture';
$keys = array('test', 'item');
$keyValuePairs = getKeyValue($string, $keys);
var_dump($keyValuePairs);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top