0

这是一个简单的例子:

$correction = "game";
$text ="Hello this is an example of a $word that starts with a $dollar sign";
$text = str_replace("\$word",$correct,$text);

如果我回显 $text,它会说:你好,这是一个以美元符号开头的游戏示例。效果很好。现在我希望能够将任何以美元符号开头的单词更改为游戏,这样它将更改所有以 $ 开头的单词并将它们变成单词“游戏”有什么想法吗?

4

4 回答 4

5

一个简单的正则表达式应该可以解决问题:

$text = preg_replace("#\$[^\b\s]+#", $correction, $text);
于 2012-07-28T02:30:21.283 回答
2

为此,您需要一个正则表达式:

$text = preg_replace( '/\$[a-z]+/i', 'game', $text);
于 2012-07-28T02:30:25.573 回答
1

使用正则表达式和 preg_replace

$correction = "game";
$text ="Hello this is an example of a \$word that starts with a \$dollar sign";
$text = preg_replace('/\$\w+/', $correction, $text);
print $text;
于 2012-07-28T02:29:44.987 回答
1

像这样:

preg_replace("/(\w*)$([a-z]+)/i", "$1$correction", $text);

注意:我没有尝试过,所以我的正则表达式可能有点缺陷。

于 2012-07-28T02:32:49.533 回答