我有一个看起来像这样的字符串:
Bla bla %yada yada% bla bla %yada yada%
有没有办法只替换前两个“%”(或最后两个)以便我可以获得下一个输出:
Bla bla <a href='link1'>yada yada</a> bla bla %yada yada%
如果有必要,最后两个“%”输出:
Bla bla <a href='link1'>yada yada</a> bla bla <a href='link2'>yada yada</a>
我不知道如何区分前两个和最后两个,所以如果我愿意,我可以用链接替换第一个或最后两个标记“%”。 我正在使用 PHP。提前致谢
问候
最佳答案
使用正则表达式(需要 PHP 5.3+):
$string = 'Bla bla %yada yada% bla bla %yada yada%';
echo preg_replace('/%([^%]*)%/', '<a href="http://example.com">$1</a>', $string, 1) . '<br>'; // to replace the first instance.
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
$links = array('http://example.com', 'http://stackoverflow.com', 'http://google.com');
$index = 0;
echo preg_replace_callback('/%([^%]*)%/', function($m) use($links, &$index){
$m[1] = '<a href="'.$links[$index].'">'.$m[1].'</a>';
$index++;
// reset the index if it exceeds (N links - 1)
if($index >= count($links)){
$index = 0;
}
return $m[1];
}, $string).'<br>'; // to replace according to your array
// ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ //
// To test with a string that contains more %% than the links
$string2 = 'Bla bla %yada yada% bla bla %yada yada% wuuut dsfsf %yada yada% sjnfsf %yada yada% jnsfds';
$links = array('http://example.com', 'http://stackoverflow.com', 'http://google.com');
$index = 0;
echo preg_replace_callback('/%([^%]*)%/', function($m) use($links, &$index){
$m[1] = '<a href="'.$links[$index].'">'.$m[1].'</a>';
$index++;
// reset the index if it exceeds (N links - 1)
if($index >= count($links)){
$index = 0;
}
return $m[1];
}, $string2).'<br>'; // to replace according to your array
关于php - 字符串替换多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16186492/