Remove Only First Word From Given String

2019-07-18 20:09发布

问题:

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

回答1:

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.



回答2:

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



回答3:

I would do something like this:

$words = explode('|', $word);
if ($words[0] === $needle) {
    unset($words[0]);
}
$word = implode('|', $words);


回答4:

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


回答5:

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



回答6:

Try this :

$index = strpos($word, '|');
$word = substr($word, 0, $index);


标签: php replace