【问题标题】:Adding a String Within a String in PHP在 PHP 中的字符串中添加字符串
【发布时间】:2011-02-22 03:40:12
【问题描述】:

我有一个基本的 PHP 字符串问题。

假设我有一个变量$story:

$story = 'this story is titled and it is really good';

如何在 'titled' 之后和 'and' 之前添加一个字符串? 如果我在另一个变量中有标题,那么说

$title = 'candy';

我可以使用什么函数或方法来做到这一点?

$story = 'this story is titled and it is really good';
$title = 'candy';
// do something
var_dump($story === 'this story is titled candy and it is really good'); // TRUE

【问题讨论】:

标签: php string add


【解决方案1】:

有几个选项。

$title = 'candy';
$story = 'this story is titled '.$title.' and it is really good';
$story = "this story is titled $title and it is really good";
$story = sprintf('this story is titled %s and it is really good', $title);

见:

如果你使用 php 和 html 并且想要打印字符串(在 php 标签之外)

this story is titled <?php echo $title ?> and it is really good

【讨论】:

  • 感谢您的简单解释,我忘了提到我想在不创建新变量的情况下这样做。感谢大家的帮助!
【解决方案2】:

您只需要使用双引号并将变量放在字符串中,如下所示:

$title = 'candy';
$story = "this story is titled $title and it is really good";

【讨论】:

  • 还有$story = 'this story is titled ' . $title . ' and it is really good';
  • 嗯,在我看到这个之前,我已将那部分添加到我的评论中 - 现在它已被删除?
  • 此解决方案假定$title 在$story 之前定义,但情况可能并非总是如此。
【解决方案3】:

我建议在您的原始字符串中使用占位符,然后用您的标题替换占位符。

所以,修改你的代码如下:

$story = "this story is titled {TITLE} and it is really good";

然后,您可以使用str_replace 将占位符替换为实际标题,如下所示:

$newStory = str_replace("{TITLE}", $title, $story);

【讨论】:

    【解决方案4】:

    简单的方法是:

    $story="this story is titled $title and it is really good".
    

    如果您询问如何找到插入位置,您可以执行以下操作:

    $i=stripos($story," and");
    $story=substr($story,0,$i)." ".$title.substr($story,$i);
    

    第三个是放置一个不太可能出现在文本中的标记,如||TITLE||。搜索它并将其替换为标题文本,例如:

    $i=stripos($story,"||TITLE||");
    $story=substr($story,0,$i).$title.substr($story,$i+9);
    

    【讨论】:

      【解决方案5】:

      利用您的朋友字符串插值(如GreenWevDev said)。

      或者,如果您需要将单词 title 替换为字符串,并且只能单独使用,您可以使用正则表达式。

      $story = preg_replace('/\btitle\b/', $title, $story);
      

      【讨论】:

        猜你喜欢
        • 2011-04-29
        • 1970-01-01
        • 2013-06-18
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-10-21
        • 1970-01-01
        相关资源
        最近更新 更多