MOrange89
MOrange89

Reputation: 23

preg_replace match exact word

I'm trying to replace words in PHP using preg_replace. When executing the code, it will replace "fuel cap for car" with "cap", as opposed to "auto parts".

$string = "fuel cap for car";

$find = array('cap', 'fuel cap for car');
$replace = array('hat', 'auto parts');

echo preg_replace($find, $replace, $string);

So, I've already tried a different method. I'm storing the original and replacement values in a database, for example:

Table

Original: automotive|motorcycle|automobile|car parts|piston|motorbike|metal fuel cap for a motorbike Replace: AUTO PARTS

Orignal: cap|baseball cap|hat|beanie Replace: HAT

The string being: fuel cap for car.

The code is:

$result = mysqli_query($connect, $query);
    while($row2 = mysqli_fetch_assoc($result)){
if(preg_match('/\b'.$row[suggestions].'\b/i', $string)){
$string = $row['description'];

But, it's replacing the string with "hat", not "auto parts"

Upvotes: 2

Views: 80

Answers (1)

Wiktor Stribiżew
Wiktor Stribiżew

Reputation: 626758

If the $find array does not contain too many items, you may solve the problem by creating an associative array from the $find and $replace arrays, and building a single regex from the array items, namely, a regex containing a single group with all the strings listed as alternatives, and then, upon finding match, replace with the corresponding $replace value.

See the PHP demo:

$string = "fuel cap for car";

$find = array('cap', 'fuel cap for car');
$replace = array('hat', 'auto parts');
$arr = array_combine($find, $replace);
usort($find, function($a, $b) {          // Longer phrases must come first
    return strlen($b) - strlen($a);
});

echo preg_replace_callback('~\b(?:' . implode('|', $find) . ')\b~', function($x) use ($arr) {
    return $arr[$x[0]];
}, $string);
// => auto parts

Upvotes: 1

Related Questions