dimanche 19 avril 2015

Php case insensitive word replacement from a sentence

I need to replace the matching words from a sentence. I am using the below but it's case sensitive. I need case insensitive.



$originalString = 'This is test.';
$findString = "is";
$replaceWith = "__";

$replacedString = (str_ireplace($findString, $replaceWith, $originalString));
// output : Th__ __ test.


Then I've tried



$replacedString = preg_replace('/\b('.preg_quote($findString).')\b/', $replaceWith, $originalString);
// output : This __ test.


It's working fine as expected but if i use $findString = "Is" or "iS" or "IS" then it's not working. Can anybody suggest me what will be the regex. to get case insensitive replacement or any other way to achieve the desire result.



UPDATED



As per @nu11p01n73R answer I have changed below but in below example it's get fall.



$originalString = 'Her (III.1) was the age of 2 years and 11 months. (shoulder a 4/5)';
$findStringArray = array("age", "(III.1)", "2", "months", "4");
foreach($findStringArray as $key => $value) {
$originalString = preg_replace('/\b('.preg_quote($value).')\b/i', "__", $originalString);
}
//Output : Her (III.1) was the __ of __ years and 11 __. (shoulder a __/5)

//Output should be : Her __ was the __ of __ years and 11 __. (shoulder a 4/5)


And also it's stopped working if I add 4/5 on $findStringArray


Aucun commentaire:

Enregistrer un commentaire