Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

php preg_replace() indexed array issue

This is the program:

$string = 'Inquiry {{inquiry:number}} is assigned to {{details_1}}';
$patterns = array();
$patterns[0] = '/({{)(.*)(}})/U';
$patterns[1] = '/({{)(.*)(}})/U';
$replacements = array();
$replacements[1] = 15;
$replacements[0] = 20;
ksort($patterns);
ksort($replacements);
echo preg_replace($patterns, $replacements, $string);

It should give the output:

Inquiry 20 is assigned to 15

But what I am getting:

Inquiry 20 is assigned to 20

I was wondering is it a problem with preg_replace?

Note: I am trying to replace the string inside {{ .. }} including the curly brackets, with the corresponding values.

like image 923
Pranay Avatar asked Jan 23 '26 04:01

Pranay


2 Answers

By default, preg_replace replace all occurrences. Simply add optional parameter “limit” to your script and it will work:

echo preg_replace( $patterns, $replacements, $string, 1 );
like image 176
fusion3k Avatar answered Jan 24 '26 17:01

fusion3k


$replArray = array(
  '{{inquiry:number}}',
  '{{details_1}}'
);

$valueArray = array (15,20);
echo str_replace($replArray,$valueArray,$patern);

If you want use the template you need parsing the variable, and checked right queue, for example {} - this right , {{} - don't right.

like image 24
Naumov Avatar answered Jan 24 '26 18:01

Naumov



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!