PHP如何自动计算输入值并用正则表达式替换?

我已经将函数设置{1}为$param1如下所示:


<?php

$lang = '{1} say not exist!';

$replaceParam = 'aaa';

function languageParam($value, $param)

{

    $value = preg_replace("/\{(.+?)\}/s", $param, $value);

    return $value;

}


echo languageParam($lang, $replaceParam );

我想知道是否可以用这种特定格式替换字符串

{numbers}


<?php

$lang = '{1} say {2} not exist!';

$param = array(

    '1' => 'aaa',

    '2' => 'bbb'

);


我的意思是,如何使函数可以对输入数组进行计数并将其替换为数字?


例如:


<?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

);


它会输出


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

是否可以?还是可以工作,但是要花费大量时间来计算和搜索字符串?


holdtom
浏览 162回答 1
1回答

回首忆惘然

您要遍历数组,然后使用数组的索引对需要替换的值进行字符串替换:<?php$lang = '{1} say {2} {3} {4}';&nbsp;$param = array(&nbsp; &nbsp; '1' => 'aaa',&nbsp; &nbsp; '2' => 'bbb',&nbsp; &nbsp; '3' => 'ccc',&nbsp; &nbsp; '4' => 'ddd');foreach($param as $index => $p) {&nbsp; $lang = str_replace('{' . $index . '}', $p, $lang);}echo $lang; //aaa say bbb ccc ddd就个人而言,我会使用方括号...<?php$lang = '[1] say [2] [3] [4]';&nbsp;$param = array(&nbsp; &nbsp; '1' => 'aaa',&nbsp; &nbsp; '2' => 'bbb',&nbsp; &nbsp; '3' => 'ccc',&nbsp; &nbsp; '4' => 'ddd');foreach($param as $index => $p) {&nbsp; $lang = str_replace("[$index]", $p, $lang);}echo $lang; //aaa say bbb ccc ddd您可以避免随后断开字符串。使用字符串索引和数字:<?php$lang = '{char_1} say {2} {char_3} {4}';&nbsp;$param = array(&nbsp; &nbsp; 'char_1' => 'aaa',&nbsp; &nbsp; '2' => 'bbb',&nbsp; &nbsp; 'char_3' => 'ccc',&nbsp; &nbsp; '4' => 'ddd');foreach($param as $index => $p) {&nbsp; $lang = str_replace('{' . $index . '}', $p, $lang);}echo $lang; //aaa say bbb ccc ddd
打开App,查看更多内容
随时随地看视频慕课网APP