Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Keep original string format when using str_ireplace

Tags:

php

I have a search feature which is coded below and i was wondering whether it is possible to keep the original formatting. for example if i have the following piece of text, "Hello, I'm new to PHP" and in my search box i type "php" in lower case, in the results it will change the original upper case 'PHP' to a lower case 'php'. is it possible to leave the string at its original state of PHP whether the user searches PhP or pHp etc.

here is the function containing the 'str_ireplace'...

function boldText($text, $kword) {
    return preg_replace('/($kword)/i', "<strong><font color='Red'>$kword</font></strong>", $text);

and here is where it is called...

 echo "<td width = 130px><b>".boldText($info['company_name'], $kword) . "</b></td> ";
 echo "<td width = 60px>".boldText($info['section_name'], $kword) . " </td>"; 
 echo "<td width = 300px>".boldText($info['question'], $kword) . " </td>";
 echo "<td width = 600px>".boldText($info['answer'], $kword) . " </td></tr>"; 

Thanks

like image 856
user1662306 Avatar asked Mar 08 '26 11:03

user1662306


2 Answers

Use regular expressions. The modifier i stands for case insensitive

echo preg_replace('/(php)/i', "<strong><font color='Red'>$1</font></strong>", 'I am new to pHp')
// returns "I am new to <strong><font color='Red'>pHp</font></strong>"

In context of your function:

function boldText($text, $kword) {
    return preg_replace('/('.$kword.')/i', "<strong><font color='Red'>$1</font></strong>", $text);
}

Single quoted strings do not parse variables that are inside!

So you need '/('.$kword.')/i' or "/($kword)/i".

Inside dobule quoted strings variables are parsed, but always be aware of strange side effects, with weird combinations.

like image 133
dan-lee Avatar answered Mar 10 '26 00:03

dan-lee


Code

$s = 'test Test teSTing ...';
echo preg_replace('~(test)~i', '<b>$1</b>', $s);

Output

test Test teSTing ...

like image 26
Glavić Avatar answered Mar 09 '26 23:03

Glavić



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!