php - 字符串替换多个值

标签 php string

我有一个看起来像这样的字符串:

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

Online demo .

关于php - 字符串替换多个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16186492/

相关文章:

php - 更新后获取以前的值 - MySql

PHP - 嵌套输出缓冲

Java 二维字符串数组 : find column where all elements are the same

php - 从一个选项卡导航到另一个选项卡

php - 如何在每个链接中添加 &ref=123

javascript - 随机选择的事件结果

java - 将字母数字字符串转换为 double

Java 数组属性越界异常

java - 如何创建属于字符串中指定类的对象?

带参数的php依赖注入(inject)