Search code examples
phpsearchpreg-replacestr-replacecase-insensitive

How to search a string using one or more search words and add a string after each match?


Given a string with one or more search strings separated by a space, I would like to case-insensitively search for matches in a text. When a match is found, I want to append <- immediately after the matched substring.

This is what I've tried:

Code

public function my_replace(string $fullText, string $searchText){

    $searches = explode(' ',$searchText);
    $replace = array();
    foreach ($searches as $i => $search){
        $replace[] = $search . '<-';
    }

    return str_ireplace($searches, $replace, $fullText);
}

Example

echo my_replace('A week ago, Elvis left the Building', 'elvis left');

Output

A week ago, elvis<- left<- the Building

Desired output

A week ago, Elvis<- left<- the Building

So I want to replace either Elvis or elvis, hence the str_ireplace, but on the output I want to show it the same way it was before.

tldr;

How do I replace a string with the same case letter if the string to replace with is actually not the same case? Does that even make sense?


Solution

  • I have made some modification in your code itself,

    This preg_replace will help you with your concern,

    Snippet

    function my_replace(string $fullText, string $searchText)
    {
        $searches = explode(' ', $searchText);
        $replace  = array();
        foreach ($searches as $i => $search) {
            $fullText = preg_replace("/$search/i", "\$0<-", $fullText);
        }
        return $fullText;
    }
    echo my_replace('A week ago, Elvis left the Building', 'elvis left');
    

    Here is working demo.

    Program Output

    A week ago, Elvis<- left<- the Building