简体   繁体   中英

PHP str_ireplace only once

I'm looking for a modified version of str_ireplace (case-insensitive) that would replace ONLY ONCE.

I read online it's doable with preg or other techniques but I'm looking for a generic function I can re-use.

Bonus: the use will be to add a link anchor tag around the word, so it would be nice if it could somehow keep the capitalization of the original word.

It sounds like you definitely want preg_replace() . If you would like you can create a user defined function:

function put_in_link($str)
{
    return preg_replace('/(linkText)/i', '<a href="/linkHref">$1</a>', $str, 1);
}

but there is kind of no reason to do this rather than preg_replace() . This call is really no more complex than a str_ireplace() call.

The last parameter was added for limiting to 1 occurrence.

PHP is a programming lanugage. Use it like a tool. Eg the functions that ship with PHP do not cover all of your bases. However, you can combine existing functions into a new function. That works pretty well.

The bottom line is, that you write yourself a function that has the missing functionality (you can change the inner of the function later you only need to take care it behaves exactly as earlier).

This is an example function actually doing what you're looking for by using stripos and substr_replace ( Demo ):

function str_ireplace_once($search, $replace, $subject, &$count = 0)
{
    $pos = stripos($subject, $search);
    if (false === $pos)
        return $subject;

    $count = 1;
    return substr_replace($subject, $replace, $pos, strlen($search));
}

And don't make any assumptions about speed unless it's really an issue for you. But stop guessing around whether it is or not. Solve your problems first, don't create additional ones out of the blue.

$text;
$word;
$replacement;
$text = substr_replace(
            $text, 
            $replacement,
            stripos($text, $word),
            strlen($word));

Should work

http://ideone.com/iIKbV

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM