gpt4 book ai didi

php - 仅从给定字符串中删除第一个单词

转载 作者:行者123 更新时间:2023-12-04 02:22:05 27 4
gpt4 key购买 nike

我正在尝试从给定的字符串中删除第一个单词。我到此为止...

$word = 'removeMe|meow|whatever';

$needle = 'removeMe';
$haystack = ''; // To replace with.

$word = str_replace( $needle, $haystack, $word );

它工作得很好,但问题是 $word 是这样的......
$word = 'removeMe|meow|removeMe|whatever';

我不想删除第二个 $needle。有可能吗? )

最佳答案

PHP preg_replace直接通过限制参数支持这一点

喜欢:

# now: removeMe|meow|removeMe|whatever

$word = preg_replace("/$needle/", $haystack, $word, 1);

# now: |meow|removeMe|whatever

如果您的针只出现 开头 ,……像一个简单的
$word = preg_replace("/^$needle/", $haystack, $word);

应该足够了。

问候

红包

关于php - 仅从给定字符串中删除第一个单词,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5210522/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com