我想用PHP替换占位符到一个给定的字符串(没有JavaScript)。
为此,我有一个可能的占位符和每个占位符的新字符串的列表:
$placeholder=array( 'firstplaceholder'=>'new text for ph1',
'2ndplaceholder'=>'new text for ph2',
'3placeholder'=>'new text for ph3',
'4placeholder'=>'new text for ph4'
...和带有占位符的字符串
$string='This is my text, here I want to use {2ndplaceholder}";通常我会这样做:
foreach($placeholder as $k=>$e)
{
if(strpos ( $string , $k){ $string=str_replace('{'.$k.'}',$e,$string);
}现在我来考虑一下运行时。如果我有一个很大的占位符列表,那么检查字符串中是否有占位符更有意义,如果我只需要很少的占位符,那么就替换它们,而不是循环每个占位符。
我怎么才能做到这一点,或者我怎么才能从字符串中创建一个数组,它包含了字符串中的所有占位符,以便只循环它们?
发布于 2021-02-02 02:17:35
现在我找到了一个更快的方法来解决这个问题。
$newstring=preg_replace_callback('/{([A-Z0-9_]+)}/',
function( $matches ) use ( $placeholders )
{
$key = strtolower( $matches[ 1 ] );
return array_key_exists( $key, $placeholders ) ? $placeholders[ $key ] : $matches[ 0 ];
},
$string
);发布于 2021-02-02 20:20:49
最简单的解决方案是在str_replace中使用key和value,但是您需要在占位符上使用大括号,以便它们匹配。
$placeholder=array( '{firstplaceholder}'=>'new text for ph1',
'{2ndplaceholder}'=>'new text for ph2',
'{3placeholder}'=>'new text for ph3',
'{4placeholder}'=>'new text for ph4');
echo str_replace(array_keys($placeholder), $placeholder, 'This is my text, here I want to use {2ndplaceholder}');或
$placeholder=array( '{firstplaceholder}'=>'new text for ph1',
'{2ndplaceholder}'=>'new text for ph2',
'{3placeholder}'=>'new text for ph3',
'{4placeholder}'=>'new text for ph4');
echo str_replace(array_keys($placeholder), array_values($placeholder), 'This is my text, here I want to use {2ndplaceholder}');如果array_values函数更易于阅读。str_replace在本地使用这些值,因此不需要它。
https://stackoverflow.com/questions/65996058
复制相似问题