Search code examples
phpregexstring-matchingplaceholdertext-extraction

Get value from square-braced key=value placeholder in text


I want to get a value from a placeholder in a string.

$string = "blah blah blha lorem ipsum [get_this_value=10] more lorem ipsum";

I would like a function that returns "10" as the lone element of a result array.

Multiple placeholders are possible, a multiple element result is desirable.

$string = "blah blah blha lorem ipsum [get_this_value=10] more lorem ipsum [get_this_value=9] etc etc";

Result: array(10, 9)


Solution

  • First you should learn about regular expressions. I can highly recommend this tutorial.

    Then you can read up on some PHP specific regex issues in PHP's documentation.

    But to get you started, this would solve your problem:

    preg_match_all("/\[[^\]=]*=(\d+)\]/", $string, $matches);
    

    Now $matches[1] will be your desired array. Note that this does not depend on the specific string get_this_value.

    For the purpose of you actually teaching yourself some regular expressions through the linked pages, I will not explain this regex in detail, but instead just tell you the concepts I have used. Unescaped square brackets [...] mark a character class. In this case (due to the ^) a negated one. \d is a built-in character class. + is a repetition quantifier. And parentheses (...) mark a capturing group.