php - 字符串仅用php中数组中的单词替换第一次出现

标签 php

$needle = array("Arr","Arr:","Arrang");
$haystack = " Arr is the proper way of Arr.";
echo str_replace($needle, "Arrangement", $haystack);

打印:Arrangement是Arrangement的正确方式

想要:Arrangement是Arr的正确方式。

最佳答案

preg_replaceimplode 和数组分隔符一起使用。分隔符 \s| 充当 语句,使用您的数组创建的正则表达式模式:

$needle = array("Arr","Arr:","Arrang");
$haystack = "Arr: is the proper way of Arr.";
echo preg_replace("/".implode("\s|",$needle)."\s/", "Arrangement ", $haystack, 1);

结果:

Arrangement is the proper way of Arr.

关于php - 字符串仅用php中数组中的单词替换第一次出现,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33317704/

相关文章:

php - 如何允许正则表达式匹配一个字符错误

php - 使用 Laravel 按天查询数据和分组

php - 使用干预图像和 laravel 5.4 圆角图像

php - jquery Ajax 成功后突出显示数据

php - 将随机访问文件代码迁移到 PHP

mysql_query() 的 PHP 登录代码错误

php - 我可以在 PHP 中混合使用 MySQL API 吗?

php - 如何在 Doctrine 2 中按日期时间排序?

php - MySQL 中的峰值投注

php - 调用mysql存储过程后报错