0

I'm trying to replace whole words in a string using str_replace, however, even letters matched in words are being replaced. i tried preg_replace, but couldn't get it to work as i have a big list of words to replace. Any help is appreciated.

$array2 = array('is','of','to','page');

$text = "homepage-of-iso-image";
echo $text1 = str_replace($array2,"",$text);

the output is : home--o-image
user2334436
  • 949
  • 5
  • 13
  • 34

2 Answers2

0

For the whole-words issue, there is a solution here using preg_replace(), and your the solution would be to add /\b to the beginning and \b/u to the end of your array-values. The case-insensitive could be handled with preg_replace_callback (see example #1), but if you are working with a small array like your example, I would just recommend duplicating the array-values.

Applied to your example:

$array2 = array(
  '/\bis\b/u',
  '/\bof\b/u',
  '/\bto\b/u',
  '/\bpage\b/u',
  '/\bIS\b/u',
  '/\bOF\b/u',
  '/\bTO\b/u',
  '/\bPAGE\b/u'
);

$text = "homepage-of-iso-image";
echo $text1 = preg_replace($array2,"",$text);
mtr.web
  • 1,505
  • 1
  • 13
  • 19
0

You could use array_diff

array array_diff ( array $array1 , array $array2 [, array $... ] )

Compares array1 against one or more other arrays and returns the values in array1 that are not present in any of the other arrays.

<?php

$remove = array('is','of','to','page');

$text   = "homepage-of-iso-image";
$parts  = explode('-', $text);

$filtered = array_diff($parts, $remove);
print implode('-', $filtered);

Output:

homepage-iso-image
Progrock
  • 7,373
  • 1
  • 19
  • 25
  • This doesn't answer the case insensitivity part of your question. See here for a solution: https://stackoverflow.com/a/1875889/3392762 – Progrock Aug 10 '18 at 21:05