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
Instead of using
$valueverbatim in the replacement, you can use the literal strings\0or$0. Just as\n/$n, for some integern, refers back to thenth capturing group of parentheses,\0/$0is expanded to the entire match. Thus, you’d haveNote that
'<b>$0</b>'uses single quotes. You can get away with double quotes here, because$0isn’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\binside 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.