Search code examples
phpregexreplaceplaceholderpreg-replace-callback

Replace placeholders in text using data fetched from the database


I am trying to match parts of a dynamically generated string and make a replacement based on the extracted information. My problem is that I can't fathom how to craft the regex.

What I have is a few different placeholder strings like the following.:

  1. [@img:1234567890]
  2. [@user:1234567890]
  3. [@file:file_name-with.ext]

Strings like this are passed through with the intent of being replaced with links, and/or more readable names. But again, I can't come up with a regex for any given one of them.

I am looking for the format: [@word:] of which I will strip the [, ], @, and word from the string so I can then turn around an query my DB accordingly for whatever it is and work with it accordingly. Just the regex bit is holding me back.


Solution

  • Not sure what you mean by generators. I always use online matchers to see that my test cases work. @Virendra almost had it except forgot to escape the [] charaters.

    /\[@(\w+):(.*)\]/
    

    You need to start and end with a regex delimeter, in this case the '/' character.

    Then we escape the '[]' which is use by regex to match ranges of characters hence the '['.

    Next we match a literal '@' symbol.

    Now we want to save this next match so we can use it later so we surround it with ().

    \w matches a word. Basically any characters that aren't spaces, punctuation, or line characters.

    Again match a literal :.

    Maybe useful to have the second part in a match group as well so (.*) will match any character any number of times, and save it for you.

    Then we escape the closing ] as we did earlier.

    Since it sounds like you want to use the matches later in a query we can use preg_match to save the matches to an array.

    $pattern = '/\[@(\w+):(.*)\]/';
    $subject = '[@user:1234567890]';
    preg_match($pattern, $subject, $matches);
    print_r($matches);
    

    Would output

    array(
        [0] => '[@user:1234567890]', // Full match
        [1] => 'user', // First match
        [2] => '1234567890' // Second match
    )
    

    An especially helpful tool I've found is txt2re