PHP: 如何在另一个字符串第一次出现之前添加子字符串?
PHP: how to add substring right before first occurrence of another string?
以这些字符串为例:
<?php
$strOne = "Place new content here: , but not past the commma.";
$strTwo = "test content";
?>
那么根据上面的字符串,如何制作一个如下所示的新字符串:
<?php
$finalstr = "Place new content here: test content, but not past the comma.";
?>
编辑
另外,假设我没有访问 $strOne 的权限,这意味着我想通过字符串函数修改它,而不是通过连接等直接修改字符串...
你的第一个例子:
$strTwo = "test content";
$strOne = "Place new content here: $strTwo, but not past the commma.";
更进一步:使用一个字符串数组,并创建一个 returns 字符串连接的函数。
$finalstr = str_replace(',', $strTwo.',', $strOne, 1);
试试 strpos
和 substr_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) "Place new content here: test content, but not past the
commma."
您可以用逗号分隔第一个字符串,然后按您想要的方式连接。要拆分,您可以使用 explode 方法:
$strArray = explode(',', $strOne,0);
$finalstr = $strArray[0].$strTwo.",".$strArray[1];
以这些字符串为例:
<?php
$strOne = "Place new content here: , but not past the commma.";
$strTwo = "test content";
?>
那么根据上面的字符串,如何制作一个如下所示的新字符串:
<?php
$finalstr = "Place new content here: test content, but not past the comma.";
?>
编辑
另外,假设我没有访问 $strOne 的权限,这意味着我想通过字符串函数修改它,而不是通过连接等直接修改字符串...
你的第一个例子:
$strTwo = "test content";
$strOne = "Place new content here: $strTwo, but not past the commma.";
更进一步:使用一个字符串数组,并创建一个 returns 字符串连接的函数。
$finalstr = str_replace(',', $strTwo.',', $strOne, 1);
试试 strpos
和 substr_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) "Place new content here: test content, but not past the commma."
您可以用逗号分隔第一个字符串,然后按您想要的方式连接。要拆分,您可以使用 explode 方法:
$strArray = explode(',', $strOne,0);
$finalstr = $strArray[0].$strTwo.",".$strArray[1];