Reputation: 6277
I want to match text from a string, whilst ignoring it's letter case. My example fails if the letter cases are not identical.
/*
$text: fOoBaR
$str: little brown Foobar
return: little brown <strong>Foobar</strong>
*/
function bold($text, $str) {
// This fails to match if the letter cases are not the same
// Note: I do not want to change the returned $str letter case.
return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).')/', "<strong>$1</strong>", $str);
}
$phrase = [
'little brown Foobar' => 'fOoBaR',
'slash / slash' => 'h / sl',
'spoon' => 'oO',
'capital' => 'CAPITAL',
];
foreach($phrase as $str => $text)
echo bold($text, $str) . '<br>';
Upvotes: 3
Views: 1874
Reputation: 16214
Ok, a couple of modifications for the line
return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).
')/', "<strong>$1</strong>", $str);
First, use modifier /i
for the case-insensitive regexp.
Second, escape $text
for the use in regexp as it might have symbols specific for the regexp (it also allows you to remove all those replacements that you have).
Third, no need in capturing the group, use the whole part of the string that fits the regexp by $0
return preg_replace('/'.preg_quote($text, '/').'/i','<strong>$0</strong>',$str);
Upvotes: 5
Reputation: 2991
Add the case insensitive modifier, i
, to the regular expression.
function bold($text, $str) {
// This fails to match if the letter cases are not the same
// Note: I do not want to change the returned $str letter case.
return preg_replace('/('.str_replace(array("/", "\\"), array("\/", "\\"), $text).')/i', "<strong>$1</strong>", $str);
}
Upvotes: 2