0

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

4

5 回答 5

3
$string = 'text more text "empty space"';
$search = 'empty space';
str_replace($search, 'empty###space', $string);
于 2012-01-03T22:10:10.260 回答
1
$somevar = "empty space";
$pattern = "/\s/";
$replacement = "###";
$somevar2 = preg_replace($pattern, $replacement, $somevar);
echo $somevar2;
于 2012-01-03T22:08:48.373 回答
1
$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

于 2012-01-03T22:09:20.893 回答
1

评论后编辑

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

$string = 'text more text "empty space"';
preg_match('/(.*)(".*?")$/', $string, $matches);
$finaltext = $matches[1] . str_replace(' ', '###', $matches[2]);
于 2012-01-03T22:10:19.470 回答
1

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

$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;
于 2012-01-03T22:30:14.887 回答