简体   繁体   中英

PHP: Replace placeholders with dynamic number (delimiters, regex)

Dear stackoverflow community,

I am currently making my own template system for a website in which I can replace template placeholders in the style of {$stuff} with php code. I have the following code for this:

/**
 * Replace a default placeholder.
 *
 * @access    public
 * @param     string $replace     Placeholder name
 * @param     string $replacement Text with which to replace placeholder.
 * @uses      $leftDelimiter
 * @uses      $rightDelimiter
 * @uses      $template
 */
public function assign($replace, $replacement) {
    $this->template = str_replace( $this->leftDelimiter .$replace.$this->rightDelimiter,
                                   $replacement, $this->template );
}

leftDelimiter and rightDelimiter in this case are {$ and }, respectively.

Now I want to add a new function that dynamically parses placeholders containing numbers - say, {$image_1}, {$image_2}, {$image_3} and lets me use the numbers contained within for my replacement code, for example so that I replace {$image_1337} with a mysql database entry from a row with id "1337".

How would I go about doing that? Extensive Google search and asking friends has, sadly, failed me due to my lack of coding vocabulary and explanation ability. It likely has to do with regular expressions, but I absolutely cannot wrap my brain around them and all attempts to construct a fitting one have failed me.

Use the preg_replace instead of the str_replace :

preg_replace("/\\{\\\$image_(\d).*?\\}/", "$1", $template)

This simple example replaces the {$image_2} with 2 etc.

If you need to use a real logic in your replacement you have two options:

  1. The Use preg_match_all to find all instances of the pattern in the template. You can then iterate over the instances, and use plain str_replace($match, $your_smart_replacement, $template)

  2. Use the preg_replace_callback that allows callback function to generate the replacement.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM