user1658787
user1658787

Reputation: 33

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

Upvotes: 3

Views: 202

Answers (3)

Lex
Lex

Reputation: 319

In the code exists offtopic error: the result value have been rewritten on not first loop iteration. And ending value of $new_string will be only last replacement.

Upvotes: 0

Antal Spector-Zabusky
Antal Spector-Zabusky

Reputation: 36612

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.

Upvotes: 2

user1647551
user1647551

Reputation: 1

I might have misunderstood your question, but if what you are struggling on is differentiating between upper-case letter (APPLE) and lower-case letter (apple), then the first thing you could do is convert the word into upper-case, or lower-case, and then run the tests to find it and put HTML tags around it. That is just my guess and maybe I completely misunderstood the question.

Upvotes: 0

Related Questions