PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Sunday, November 20, 2022

[FIXED] How to count input values automatically and replace it without regex?

 November 20, 2022     php, preg-replace, regex     No comments   

Issue

I have set the function to replace {1} into $param1 like this:

<?php
$lang = '{1} say not exist!';
$replaceParam = 'aaa';
function languageParam($value, $param)
{
    $value = preg_replace("/\{(.+?)\}/s", $param, $value);
    return $value;
}

echo languageParam($lang, $replaceParam );

I want to know if it's possible to replace the string by this specific format:
{numbers}
Like this:

<?php
$lang = '{1} say {2} not exist!';
$param = array(
    '1' => 'aaa',
    '2' => 'bbb'
);

I means, how to make the function can count input array and replace them by numbers?

For example:

<?php
$lang = '{1} say {2} {3} {4}'; //maybe have {5}, {6}...etc
$param = array(
    '1' => 'aaa',
    '2' => 'bbb',
    '3' => 'ccc',
    '4' => 'ddd'
//and '5', '6'...etc
);

And it will output

aaa say bbb ccc ddd //....and more

Is it possible? Or it can work but will cost long time to count and search the strings?


Solution

You want to loop through the array and then do a string replace on the value you need to replace, using the index of the array:

<?php
$lang = '{1} say {2} {3} {4}'; 
$param = array(
    '1' => 'aaa',
    '2' => 'bbb',
    '3' => 'ccc',
    '4' => 'ddd'
);

foreach($param as $index => $p) {
  $lang = str_replace('{' . $index . '}', $p, $lang);
}

echo $lang; //aaa say bbb ccc ddd

Personally, I would use square brackets...

<?php
$lang = '[1] say [2] [3] [4]'; 
$param = array(
    '1' => 'aaa',
    '2' => 'bbb',
    '3' => 'ccc',
    '4' => 'ddd'
);

foreach($param as $index => $p) {
  $lang = str_replace("[$index]", $p, $lang);
}

echo $lang; //aaa say bbb ccc ddd

You can avoid breaking out the string then.

With string indexes and numeric:

<?php

$lang = '{char_1} say {2} {char_3} {4}'; 
$param = array(
    'char_1' => 'aaa',
    '2' => 'bbb',
    'char_3' => 'ccc',
    '4' => 'ddd'
);

foreach($param as $index => $p) {
  $lang = str_replace('{' . $index . '}', $p, $lang);
}

echo $lang; //aaa say bbb ccc ddd


Answered By - Adam
Answer Checked By - Marilyn (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing