Chiel
Chiel

Reputation: 83

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;

}

Upvotes: 0

Views: 79

Answers (1)

mike.k
mike.k

Reputation: 3457

I did it by building the various replacement cases on the fly.

$content = 'Apples is the plural of apple, apples are delicious';

$rewrites = array(
    array('apple', 'blueberry'),
    array('apple', 'raspberry')
);

echo "$content\n";
foreach ($rewrites as $rule) {
    $source = $rule[0];
    $target = $rule[1];

    // word and Word
    $find = array($source, ucfirst($source));
    $replace = array($target, ucfirst($target));

    // add plurals for source
    if (preg_match('/y$/', $source)) {
        $find[] = preg_replace('/y$/', 'ies', $source);
    } else {
        $find[] = $source . 's';
    }
    $find[] = ucfirst(end($find));

    // add plurals for target
    if (preg_match('/y$/', $target)) {
        $replace[] = preg_replace('/y$/', 'ies', $target);
    } else {
        $replace[] = $target . 's';
    }
    $replace[] = ucfirst(end($replace));

    // pad with regex
    foreach ($find as $i => $word) {
        $find[$i] = '/\b' . preg_quote($word, '/') . '\b/';
    }

    echo preg_replace($find, $replace, $content) . "\n";
}

Output:

Apples is the plural of apple, apples are delicious
Blueberries is the plural of blueberry, blueberries are delicious
Raspberries is the plural of raspberry, raspberries are delicious

Upvotes: 1

Related Questions