【问题标题】:Replace empty spaces with ### from Text between " " in a string in PHP用###替换PHP中字符串中“”之间的文本中的空格
【发布时间】:2012-01-03 22:05:23
【问题描述】:

我有一个这样的字符串text more text "empty space"。 如何替换"empty space" 中的空格,并且只用### 替换这个空格?

【问题讨论】:

  • 请不要在您的帖子上签名。
  • 我只想替换“”之间的文本中的空格。所以结果应该看起来像 text more text "empty###space"
  • 这个问题总体上令人困惑。而不是“文本更多文本”..提供一个真正的例子。 “这是一个文本字符串,我希望以某种方式对其进行更改。”这会准确地显示字符串的更改方式。
  • @user1067506:请回答我的问题。

标签: php regex preg-replace preg-split


【解决方案1】:
$string = 'text more text "empty space"';
$search = 'empty space';
str_replace($search, 'empty###space', $string);

【讨论】:

  • @George 文字会变……“空白”只是为了演示
  • @user1067506 我从您的评论中看到,这在原始帖子中并不清楚。正在研究另一个解决方案。
  • @George 是的。也许我没有准确描述这个问题。很抱歉。
【解决方案2】:

这个怎么样,没有正则表达式:

$text = 'foo bar "baz quux"';
$parts = explode('"', $text);
$inQuote = false;

foreach ($parts as &$part) {
    if ($inQuote) { $part = str_replace(' ', '###', $part); }
    $inQuote = !$inQuote;
}

$parsed = implode('"', $parts);
echo $parsed;

【讨论】:

    【解决方案3】:
    $somevar = "empty space";
    $pattern = "/\s/";
    $replacement = "###";
    $somevar2 = preg_replace($pattern, $replacement, $somevar);
    echo $somevar2;
    

    【讨论】:

    • 这将做所有的空间。如果这是在一大块文本中,则模式将为空\sspace,替换为空###space
    • 请看我上面的评论。
    【解决方案4】:
    $string = "My String is great";
    $replace = " ";
    $replace_with = "###";
    
    $new_string = str_replace($replace, $replace_with, $string);
    

    这应该为你做。 http://www.php.net/manual/en/function.str-replace.php

    【讨论】:

    • 看到更新后的问题,乔治提供了正确答案。
    • 请看我上面的评论。
    【解决方案5】:

    在你参加比赛后编辑

    也许这不是最好的解决方案,但你可以这样做:

    $string = 'text more text "empty space"';
    preg_match('/(.*)(".*?")$/', $string, $matches);
    $finaltext = $matches[1] . str_replace(' ', '###', $matches[2]);
    

    【讨论】:

      猜你喜欢
      • 2018-07-09
      • 2015-08-09
      • 1970-01-01
      • 1970-01-01
      • 2013-05-09
      • 1970-01-01
      • 1970-01-01
      • 2015-04-08
      • 1970-01-01
      相关资源
      最近更新 更多