【问题标题】:PHP: how to add substring right before first occurrence of another string?PHP:如何在第一次出现另一个字符串之前添加子字符串?
【发布时间】:2015-12-08 10:11:34
【问题描述】:

以这些字符串为例:

<?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,这意味着我想通过字符串函数而不是直接通过连接等方式修改字符串...

【问题讨论】:

  • 你试过了吗?
  • 不确定 php 有哪些功能可以做到这一点..

标签: php string variables substring


【解决方案1】:
$finalstr = str_replace(',', $strTwo.',', $strOne, 1);

【讨论】:

    【解决方案2】:

    你可以用逗号分割第一个字符串,然后按照你想要的方式连接。要拆分,您可以使用explode 方法:

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

    【讨论】:

      【解决方案3】:

      试试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) "在此处放置新内容:测试内容,但不超过 逗号。”

      【讨论】:

      • 你先生很聪明。我知道我可以开始一个新字符串并直接修改它,但我想要一个像你这样的字符串函数的解决方案,谢谢。
      • 将在 3 分钟内完成。
      【解决方案4】:

      你的第一个例子:

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

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

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2023-03-15
        • 2011-12-19
        • 1970-01-01
        • 1970-01-01
        • 2011-11-02
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多