如何使用变量将一个字符串替换为另一个字符串


How to generically replace a string with another using a variable

问题:

我一直在弄清楚如何使用 PHP 将变量中的字符串添加到许多不同的字符串中。

变量:

$insert = 'icon-white';

字符串位于名为 $hyperlink 的变量中:

$hyperlink = '<i class="icon-home"></i>';

期望输出:

<i class="icon-home icon-white"></i>

欢迎任何建议,并提前感谢。

老实说,在这个特定问题上,我没有看到正则表达式的好处,所以我选择忽略这一方面; 主要关注点似乎是在最后一个"字符之前插入新字符串,这可以通过以下方法实现:

$hyperlink = '<i class="icon-home"></i>';
$insert = ' icon-white'; // I've explicitly prefixed the new string with a space
$pos = strripos($hyperlink,'"',0);
echo substr_replace($hyperlink,$insert,$pos,0)

如果你愿意,那么,为了将来使用,这里有一个函数,它将在给定字符($needle最后一次出现之前将给定的字符串($new)插入到另一个字符串($haystack)中:

function insertBeforeLast($haystack,$needle,$new){
    if (!$haystack || !$needle || !$new){
        return false;
    }
    else {
        return substr_replace($haystack,$new,strripos($haystack,$needle),0);
    }
}
    echo insertBeforeLast('abcdefg','e','12',' ');

函数中 substr_replace() 的右括号之前的0表示新插入的字符串将在原始字符串中覆盖的字符数。

<小时 />

编辑以修改上述函数以明确提供覆盖作为选项:

function insertBeforeLast($haystack,$needle,$new, $over){
    if (!$haystack || !$needle || !$new){
        return false;
    }
    else {
        $over = $over || 0;
        return substr_replace($haystack,$new,strripos($haystack,$needle),$over);
    }
}
    echo insertBeforeLast('abcdefg','e','12',0);

引用:

  • strripos() .
  • substr_replace() .

这是如何使用 php 函数来满足preg_replace()您的需求:

$ php -a
Interactive shell
php > $oldvar = '<i class="icon-home"></i>';
php > $newvar = preg_replace('/(.*?".*?)"(.*)/', ''1 icon-white"'2 ', $oldvar);
php > echo $newvar;
<i class="icon-home icon-white"></i> 

渲染输出时,你可以这样做;

<i class="icon-home <?= $insert ?>"></i>

如果你不希望它是有条件的。

如果你有一个变量;

$i = '<i class="icon-home"></i>';

你可以做;

$i = '<i class="icon-home ${insert}"></i>';