Search code examples
phpstringvariablessubstringlimit

Insert substring right before first occurrence of another string


Take for example these strings:

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

So based on the strings above, how do make a new string that looks like this:

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

EDIT

Also, lets assume I don't have access to $strOne, meaning I want to modify it via string functions not directly the string via concatenation etc...


Solution

  • Try a combination of strpos and 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);
    }
    

    Output:

    string(63) "Place new content here: test content, but not past the commma."