jeudi 29 décembre 2016

Replacing capitalized and non-capitalized string with preg_replace

I'm working on a project where I have a string with content e.g. $content, and an array with words (with no capitals) e.g. $rewrites.

What I want to achieve, example case:

$content contains a string with the following text: 'Apples is the plural of apple, apples are delicious'.

$rewrites contains an array with the following data: 'apple', 'blueberry'.

Now I want to create a function that replaces all apple for something else, e.g. raspberry. But, in the string, there is Apples, which won't be replaced using preg_replace. Apples should be replaced with Raspberry (mention the capital R).

I tried different methods, and patterns but it won't work.

Currently I have the following code

foreach($rewrites as $rewrite){
      if(sp_match_string($rewrite->name, $content) && !in_array($rewrite->name, $spins) && $rewrite->name != $key){
        /* Replace the found parameter in the text */
        $content = str_replace($rewrite->name, $key, $content);

        /* Register the spin */
        $spins[] = $key;
      }
    }

function sp_match_string($needle, $haystack) {

 if (preg_match("/\b$needle\b/i", $haystack)) {
   return true;
 }
return false;

}

Aucun commentaire:

Enregistrer un commentaire