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
4
Answers
Adding some debug lines should help:
output:
Here:
WITHOUT Replace -title-: :
means that the text between-
is replaced by the text between:
, effectively removing the texttitle
.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:
If you look at the result of your first
preg_match_all()
you will see you have all you need in the$matches
arrayThe
$matches
arraySo you can simplify the code to
And the result is
It isn’t a job for
preg_match_all
but forpreg_replace_callback
(it’s a replacement task yes or not?).demo
The pattern uses a capture group (capture group 1) to extract content between square brackets. The second parameter of
preg_replace_callback
is the callback function that tests if the captured content$m[1]
exists as key in the array$get_product
and returns the corresponding value or the full match$m[0]
.Other way without regex at all (since you are looking for literal strings):
demo