我知道这可能是一个常见的问题,但我找不到我想要的确切答案。
我有下面的字符串。
#|First Name|#
Random Text
#|Last Name|#
我想做的是将#|
&CCD_ 2,并将整个字符串替换为一个值。这必须在一个数组中,这样我就可以循环遍历它们。
因此,作为一个例子,我有:
#|First Name|#
处理后,我希望它是:
John
因此,主要逻辑是使用First Name值从数据库中打印出一个值。
有人能帮我吗。
这是我尝试过的代码:
preg_match('/#|(.*)|#/i', $html, $ret);
感谢
除了使正则表达式不贪婪和转义竖条之外,您还需要preg_replace_callback()
来实现这一点:
$replacements = array( 'John', 'Smith');
$index = 0;
$output = preg_replace_callback('/#'|(.*?)'|#/i', function( $match) use ($replacements, &$index) {
return $replacements[$index++];
}, $input);
这将输出:
string(24) "John
Random Text
Smith"
$string = '#|First Name|#
Random Text
#|Last Name|#';
$search = array(
'#|First Name|#',
'#|Last Name|#',
);
$replace = array(
'John',
'Smith',
);
$string = str_replace($search, $replace, $string);