仅从给定字符串中删除第一个单词 [英] Remove Only First Word From Given String

查看:51
本文介绍了仅从给定字符串中删除第一个单词的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm trying to remove first word from given string. I'm done so far...

$word = 'removeMe|meow|whatever';

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

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

效果很好,但问题是 $word 是这样的......

It's working great, but problem is when $word is something like this...

$word = 'removeMe|meow|removeMe|whatever';

我不想移除第二个$needle.有可能吗?)

I don't want to remove second $needle. Is it possible and how? )

推荐答案

遗憾的是 PHP 默认不支持.这是一个函数:

Unfortunately PHP doesn't support this by default. Here's a function doing it:

function str_replace_once($needle, $replace, $haystack){
    $pos = strpos($haystack, $needle);
    if ($pos === false) {
        return $haystack;
    }
    return substr_replace($haystack, $replace, $pos, strlen($needle));
}

如果只想替换字符串开头的文本:

If you want to replace the text only at the beginning of the string:

$str = preg_replace('/^'.preg_quote($word, '/').'/', '', $str);

如果您的字符串实际上是一个 | 分隔的列表,请参阅 @lonesomeday 的答案.

If your string is actually a |-separated list, see @lonesomeday's answer.

这篇关于仅从给定字符串中删除第一个单词的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆