Search code examples
phpregexpreg-match

Replace text with preg_match_all using PHP


I have this string:

The product title is [title] and the price is [price] and this product link is [link]

and I have a variable called $get_product whch contain associated array.

Now, I want to replace [xxx] from the string with the $get_product[xxx] variable key. What I am doing this:

$pattern = '/\[(.*?)\]/';
preg_match_all($pattern, $optimization_prompt, $matches);

if( $matches ) {
    foreach( $matches as $key => $match ) {
        for( $i = 0; $i < count($match); $i++ ) {
            if( preg_match_all($pattern, $match[$i], $matches)  ) {
                // with bracket 
                $remove_bracket         = trim( $match[$i], '[]');
                $optimization_prompt    = str_replace( $match[$i], isset( $get_product[$remove_bracket] ) ? $get_product[$remove_bracket] : '', $optimization_prompt);
            } else {
                // Without bracket
                $remove_bracket         = trim( $match[$i], '[]');
                $optimization_prompt    = str_replace( $match[$i], '', $optimization_prompt);
            }
        }
    }
}

Its returning me:

<pre>The product  is  Infaillible Full Wear327 Cashm and the  is  10.49  and this product  is  https://www.farmaeurope.eu/infaillible-full-wear327-cashm.html</pre>

The result is okay but its removed the actual text called title, price link


Solution

  • I don't know what you're trying to do there, but it's totally overcomplicated it seems. Here's a simple solution w/ comments:

    $pattern = '/\[.*?\]/';
    $get_product = ['title' => 'answer', 'price' => 666, 'link' => 'https://stackoverflow.com'];
    $optimization_prompt = 'The product title is [title] and the price is [price] and this product link is [link]';
    preg_match_all($pattern, $optimization_prompt, $matches);
    
    // Cycle through full matches
    foreach($matches[0] as $match) {
        // Remove the brackets for the array key
        $product_key = trim($match, '[]');
        
        // If product key available, replace it in the text
        $optimization_prompt = str_replace($match, $get_product[$product_key] ?? '', $optimization_prompt);
    }
    
    // Result: The product title is answer and the price is 666 and this product link is https://stackoverflow.com
    echo $optimization_prompt;