【发布时间】:2018-11-25 13:08:31
【问题描述】:
我从 PHP 中的 preg_replace 开始,我想知道如何只用指定的数组值替换第一个匹配的数组键,因为我将 preg_replace 更改次数参数设置为“1”,而且它改变了不止一次。我还将字符串拆分为单个单词,并且正在逐个检查它们:
<?php
$internal_message = 'Hey, this is awesome!';
$words = array(
'/wesome(\W|$)/' => 'wful',
'/wful(\W|$)/' => 'wesome',
'/^this(\W|$)/' => 'that',
'/^that(\W|$)/' => 'this'
);
$splitted_message = preg_split("/[\s]+/", $internal_message);
$words_num = count($splitted_message);
for($i=0; $i<$words_num; $i++) {
$splitted_message[$i] = preg_replace(array_keys($words), array_values($words), $splitted_message[$i], 1);
}
$message = implode(" ", $splitted_message);
echo $message;
?>
我希望这是输出:
嘿,这太糟糕了
(后缀一变,一字变停)
不是这个:
嘿,这太棒了
(两个后缀变化,两个单词变化并回到原来的单词和后缀......)
也许我可以简化这段代码?我也无法更改数组键和值的顺序,因为很快会有更多的后缀和单个单词要更改。我是 php 编码的新手,我会感谢任何帮助;>
【问题讨论】:
-
Nvrmind,像魅力一样工作!谢谢;>
-
@WiktorStribiżew 特殊字符现在对我来说非常重要,没有它们我将无法使用这段代码做任何事情
-
您应该从一开始就提到您正在使用 Unicode 文本,这是一个重要的细节。
标签: php arrays string preg-replace preg-split