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
$get_product[$remove_bracket]to get the value from the varilable which I want to replace.elsebranch? (The one with the comment "without bracket") ?[xxx]with the$get_product[xxx]value.