daGrevis daGrevis - 1 year ago 66
PHP Question

Remove Only First Word From Given String

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

Answer Source

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.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download