Replace (add) case sensitive words from arrays

I am new to php and especially for regex. My goal is to automatically enrich texts with hints for the "keywords" that are listed in arrays.

So far I have come.

$pattern = array("/\bexplanations\b/i",
            "/\btarget\b/i", 
            "/\bhints\b/i",
            "/\bhint\b/i",
);

$replacement = array("explanations <i>(Erklärungen)</i>",
            "target <i>Ziel</i>", 
            "hints <i>Hinsweise</i>",
            "hint <i>Hinweis</i>",
);

$string = "Target is to add some explanations (hints) from an array to 
this text. I am thankful for every hint.";

echo preg_replace($pattern, $replacement, $string);

returns:

target <i>Ziel</i> is to add some explanations <i>(Erklärungen)</i> (hints <i>Hinsweise</i>) from an array to this text. I am thankful for every hint <i>Hinweis</i>

1) In general, I wonder if there are more elegant solutions (ultimately, without replacing the original word)? In a later state, arrays will contain more than 1000 elements ... and come from mariadb.

2) How can I get the word “Goals” to receive case-sensitive treatment? (without duplicating the length of the arrays).

Sorry for my english and thank you very much in advance.

+4
source share
2

.

- PHP:

$pattern = array("/\b(explanations)\b/i", "/\b(target)\b/i", "/\b(hints)\b/i", "/\b(hint)\b/i", ); 
$replacement = array('$1 <i>(Erklärungen)</i>', '$1 <i>Ziel</i>', '$1 <i>Hinsweise</i>', '$1 <i>Hinweis</i>', ); 
$string = "Target is to add some explanations (hints) from an array to this text. I am thankful for every hint."; 
echo preg_replace($pattern, $replacement, $string);

, , , .

, , , ( Targets, Target ..)

+1

, , ( ) . , , . , :

// Translation array with all keys lowercase
$trans = [ 'explanations' => 'Erklärungen',
           'target' => 'Ziel',
           'hints' => 'Hinsweise',
           'hint' => 'Hinweis'
];

$parts = preg_split('~\b~', $text);

$partsLength = count($parts);

// All words are in the odd indexes
for ($i=1; $i<$partsLength; $i+=2) {
    $lcWord = strtolower($parts[$i]);

    if (isset($trans[$lcWord]))
        $parts[$i] .= ' <i>(' . $trans[$lcWord] . ')</i>';
}

$result = implode('', $parts);

, , ( , ), , preg_match_all preg_split , , :

preg_match_all('~mushroom pie\b|\w+|\W*~iS', $text, $m);

$parts = &$m[0];
$partsLength = count($parts);

$i = 1 ^ preg_match('~^\w~', $parts[0]);

for (; $i<$partsLength; $i+=2) {

...

( ( ), .)

+2

Source: https://habr.com/ru/post/1657846/


All Articles