Search and Replace with Regex

I am trying to search through text for a specific word and then add a html tag around that word.For example if i had the string "I went to the shop to buy apples and oranges" and wanted to add html bold tags around apples.

The problem, the word i search the string with is stored in a text file and can be uppercase,lowercase etc.When i use preg_replace to do this i manage to replace it correctly adding the tags but for example if i searched for APPLES and the string contained "apples" it would change the formatting from apples to APPLES, i want the format to stay the same.

I have tried using preg_replace but i cant find a way to keep the same word casing.This is what i have:

foreach($keywords as $value)
    {
        $pattern = "/\b$value\b/i";
        $replacement = "<b>$value</b>";
        $new_string = preg_replace($pattern, $replacement, $string);
    }

So again if $value was APPLES it would change every case format of apples in the $string to uppercase due to $replacemant having $value in it which is "APPLES".

How could i achieve this with the case format staying the same and without having to do multiple loops with different versions of case format?

Thanks

Answers


Instead of using $value verbatim in the replacement, you can use the literal strings \0 or $0. Just as \n/$n, for some integer n, refers back to the nth capturing group of parentheses, \0/$0 is expanded to the entire match. Thus, you'd have

foreach ($keywords as $value) {
  $new_string = preg_replace("/\\b$value\\b/i", '<b>$0</b>', $string);
}

Note that '<b>$0</b>' uses single quotes. You can get away with double quotes here, because $0 isn't interpreted as a reference to a variable, but I think this is clearer. In general, you have to be careful with using a $ inside a double-quoted string, as you'll often get a reference to an existing variable unless you escape the $ as \$. Similarly, you should escape the backslash in \b inside the double quotes for the pattern; although it doesn't matter in this specific case, in general backslash is a meaningful character within double quotes.


Need Your Help

Customize Jetpack JSON API: How can I add more posts?

json wordpress jetpack

I'm using the Jetpack JSON API. At the moment I can get 20 posts through the JSON API. How can I get more then 20 posts? Can I change this by editing the Jetpack php files?

Can Text Fields Auto-Recognize Phone Numbers and Links?

objective-c cocoa

Is it possible for a text field to auto-recognize phone numbers and links?

About UNIX Resources Network

Original, collect and organize Developers related documents, information and materials, contains jQuery, Html, CSS, MySQL, .NET, ASP.NET, SQL, objective-c, iPhone, Ruby on Rails, C, SQL Server, Ruby, Arrays, Regex, ASP.NET MVC, WPF, XML, Ajax, DataBase, and so on.