在另一个字符串第一次出现之前插入子字符串


Insert substring right before first occurrence of another string

以以下字符串为例:

  $strOne = "Place new content here:  , but not past the commma.";
  $strTwo = "test content";

因此,基于上面的字符串,如何制作一个看起来像这样的新字符串:

  $finalstr = "Place new content here:  test content, but not past the comma.";

编辑

此外,假设我没有访问$strOne的权限,这意味着我想通过字符串函数修改它,而不是通过串联等直接修改字符串。

您可以用逗号分割第一个字符串,然后按您想要的方式进行concat。要进行拆分,可以使用分解方法:

$strArray = explode(',', $strOne, 2);
$finalstr = $strArray[0].$strTwo.",".$strArray[1];

尝试strpossubstr_replace的组合?

$strOne = "Place new content here:  , but not past the commma.";
$strTwo = "test content";
// find the position of comma first
$pos = strpos($strOne, ',');
if ($pos !== false)
{
     // insert the new string at the position of the comma
     $newstr = substr_replace($strOne, $strTwo, $pos, 0);
     var_dump($newstr);
}

输出:

string(63("在此处放置新内容:测试内容,但不超过commma。">

str_replace()没有限制替换数量的功能。preg_replace()虽然不是在干草堆中找到针头的必要条件,但确实允许更换限制。使用explode()不是一种可怕的方法,但如果你使用它,你应该将爆炸限制在2。我不喜欢在寻找字符串结果时生成临时数组的间接性。

代码:(演示(

$strOne = "Place new content here:  , but not past the commma.";
$strTwo = "test content";
echo preg_replace('/,/', "$strTwo,", $strOne, 1);

您可以使用preg_replace('/(?=,)/', $strTwo, $strOne, 1)来避免在替换字符串中提及针,但regex的性能会更差,因为在遍历haystring字符串时,每一步都会执行先行检查——这并不好。

如果针字符串可能包含对正则表达式引擎具有特殊意义的字符,则使用'/' . preg_quote($yourNeedle, '/') . '/'作为模式。


如果你的指针更多变,那么使用同样的正则表达式技术。如果想要在文本块中找到第一个标签子串,只需搜索第一个出现的#,然后是一个(或多个(单词字符。如果您想强制#前面有一个空格,您也可以添加它。您可以使用前瞻性来避免将指针复制到替换参数中,但这可能会执行得稍慢,具体取决于干草堆字符串的质量。

输入:

$strOne = "Programming requires life long learning #learning #stackoverflow #programming";
$strTwo = "'n'n";

代码:(演示(

echo preg_replace('/#'w/', "$strTwo$0", $strOne, 1);
// or echo preg_replace('/ (#'w)/', "$strTwo$1", $strOne, 1); // to replace the preceding space with 2 newlines

或者:(演示(

echo preg_replace('/ 'K(?=#'w)/', $strTwo, $strOne, 1);

使用您的第一个示例:

$strTwo = "test content";
$strOne = "Place new content here: $strTwo, but not past the commma.";

更进一步:使用一个字符串数组,并创建一个返回字符串串联的函数。

$finalstr = str_replace(',', $strTwo.',', $strOne, 1);