Remove Only First Word From Given String

2019-07-18 19:53发布

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 );

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

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

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

标签: php replace
6条回答
手持菜刀,她持情操
2楼-- · 2019-07-18 20:23

Try this :

$index = strpos($word, '|');
$word = substr($word, 0, $index);
查看更多
地球回转人心会变
3楼-- · 2019-07-18 20:24

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);

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

查看更多
Juvenile、少年°
4楼-- · 2019-07-18 20:25

I would do something like this:

$words = explode('|', $word);
if ($words[0] === $needle) {
    unset($words[0]);
}
$word = implode('|', $words);
查看更多
甜甜的少女心
5楼-- · 2019-07-18 20:30

PHPs preg_replace supports this directly through the limit parameter

like:

# now: removeMe|meow|removeMe|whatever

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

# now: |meow|removeMe|whatever

If your needle only appears at the beginning, sth. like a simple

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

should suffice.

Regards

rbo

查看更多
冷血范
6楼-- · 2019-07-18 20:30

I was gonna go with an explode, implode, but this is better and shorter. It will leave the first pipe symbol though.

echo $string = strstr($string , '|');

If your string is space separated, just replace the pipe with a space

查看更多
疯言疯语
7楼-- · 2019-07-18 20:31

Third parameter of the explode function limits how many times the word will be split. This allowed a very clean solution for me. From php.net:

If limit is set and positive, the returned array will contain a maximum of limit elements with the last element containing the rest of string.

$split = explode('|', $word, 2);
$word = $split[1];
查看更多
登录 后发表回答