【问题标题】:string manipulation in PHP: replace only the first occurrence of a word in a stringPHP中的字符串操作:仅替换字符串中第一次出现的单词
【发布时间】:2010-07-04 18:33:19
【问题描述】:

如果我只想替换字符串中第一次出现的单词该怎么办。 例如:我想用 kiran 更改字符串中第一次出现的 heelo。

input string == **"hello world i am a noob hello to all"**
output string == **"kiran world i am a noob hello to all"**

str_replace 不起作用。

【问题讨论】:

  • 请发布您的代码。你所说的“不工作”到底是什么意思?
  • “不工作”是什么意思?你还尝试过什么?
  • str_replace 正在改变“hello”的出现。我只需要将第一个 'hello' 替换为 'kiran'

标签: php string


【解决方案1】:

您可以使用preg_replace。此函数的第 4 个参数允许您设置替换发生的次数。

$output = preg_replace( "/$find/", $replace, $input, 1 );

如果您不想在搜索字符串中解释正则表达式元字符,请使用:

$output = preg_replace( "/\\Q$find\\E/", $replace, $input, 1 );

【讨论】:

  • 如果 hello 和 kiran 都存储在字符串中会怎样。说 $find='你好'; $replace='基兰'; $input='你好世界我是一个菜鸟你好';
  • 我使用了 preg_replace('/' + $find + '/', $replace, $input, 1);但它在该行显示错误“C:\wamp\www\test\e.php 中的分隔符不能是字母数字或反斜杠”
  • 我已经更新了我的答案以说明您提到的情况。
【解决方案2】:

您可以使用stripos()substr_replace()

$str = "hello world i am a noob hello to all";
$needle = 'hello';
echo substr_replace($str, 'kiran', stripos($needle, $str), strlen($needle));

给予

kiran world i am a noob hello to all

stripos() 给出子字符串第一次出现的索引(不区分大小写),substr_replace() 用给定参数替换索引i 和长度n 处的子字符串。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2014-03-21
    • 2011-08-25
    • 2021-04-17
    • 1970-01-01
    • 2016-12-19
    • 2016-05-07
    相关资源
    最近更新 更多